Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to calculate amount of even numbers in given range

Tags:

c

math

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?

like image 792
Fdr Avatar asked Apr 21 '10 11:04

Fdr


1 Answers

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.

like image 123
9 revs, 2 users 97% Avatar answered Sep 21 '22 13:09

9 revs, 2 users 97%