Simplest way to calculate amount of even numbers in given range

前端 未结 16 2429
小蘑菇
小蘑菇 2021-02-13 14:10

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\

16条回答
  •  忘了有多久
    2021-02-13 14:46

    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 );
    }
    

提交回复
热议问题