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\
Oh well, why not:
#include
int ecount( int begin, int end ) {
assert( begin <= end );
int size = (end - begin) + 1;
if ( size % 2 == 0 || begin % 2 == 1 ) {
return size / 2;
}
else {
return size / 2 + 1;
}
}
int main() {
assert( ecount( 1, 5 ) == 2 );
assert( ecount( 1, 6 ) == 3 );
assert( ecount( 2, 6 ) == 3 );
assert( ecount( 1, 1 ) == 0 );
assert( ecount( 2, 2 ) == 1 );
}