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.