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\
int even = (0 == begin % 2) ? (end - begin) / 2 + 1 : (end - begin + 1) / 2;
Which can be converted into:
int even = (end - begin + (begin % 2)) / 2 + (1 - (begin % 2));
EDIT: This can further simplified into:
int even = (end - begin + 2 - (begin % 2)) / 2;
EDIT2: Because of the in my opinion somewhat incorrect definition of integer division in C (integer division truncates downwards for positive numbers and upwards for negative numbers) this formula won't work when begin is a negative odd number.
EDIT3: User 'iPhone beginner' correctly observes that if begin % 2
is replaced with begin & 1
this will work correctly for all ranges.