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\
Let's look at this logically ...
We have four cases ...
odd -> odd eg. 1 -> 3 answer: 1
odd -> even eg. 1 -> 4 answer: 2
even -> odd eg. 0 -> 3 answer: 2
even -> even eg. 0 -> 4 answer: 3
The first three cases can be handled simply as ...
(1 + last - first) / 2
The fourth case does not fall quite so nicely into this, but we can fudge around a little bit for it quite easily ...
answer = (1 + last - first) / 2;
if (both first and last are even)
answer++;
Hope this helps.
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)
Pseudo code (i'm no C coder):
count = 0;
foreach(i in range){
if(i % 2 == 0){
count++;
}
}
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.