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 count of even numbers between 0 and n is [n/2] + 1. Therefore the count of even numbers between (n + 1) and m is ([m/2] + 1) - ([n/2] + 1) = [m/2] - [n/2].
For count of even numbers between m and n the answer therefore would be [m/2] - [(n - 1)/2].
The [x] is taken to the direction of -\infty. Beware that the usual C integer division is not doing right in our case: a/2
is rounded towards zero, not -\infty, so the result will be not [a/2] for teh case of negative a.
This should be the simplest calculation; works for negative numbers, too. (Needs however that m >= n.) Doesn't contain if
s and ?:
s.
If you don't consider negative numbers, you can use just m/2 - (n+1)/2 + 1
, otherwise floor(m/2.0) - floor((n-1)/2.0)