What is the simplest way to calculate the amount of even numbers in a range of unsigned integers?
An example: if range is [0...4] then the answer is 3 (0,2,4)
I\
The answer:
(max - min + 2 - (max % 2) - (min % 2)) / 2
A short explanation:
odd..odd yields (length - 1) / 2
length = max - min + 1
Therefore, the answer is (length - 1) / 2
plus 1/2
for even min plus 1/2
for even max.
Note that (length - 1) / 2 == (max - min) / 2
, and the "bonuses" are (1 - (min % 2)) / 2
and (1 - (max % 2)) / 2
. Sum this all up and simplify to obtain the answer above.