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'm having hard time to think of any simple way. The only solution I came up involved couple of if-statements. Is there a simple line of code that can do this without if-statements or ternary operators?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With