Simplest way to calculate amount of even numbers in given range

前端 未结 16 2441
小蘑菇
小蘑菇 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:58

    The first even number in the range is: (begin + 1) & ~1 (round begin up to even number).

    The last even number in the range is: end & ~1 (round end down to even number).

    The total number of even numbers in the range is therefore: (end & ~1) - ((begin + 1) & ~1) + 1.

    int num_evens = (end & ~1) - ((begin + 1) & ~1) + 1;
    

提交回复
热议问题