Simplest way to calculate amount of even numbers in given range

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

    The range is always [2a+b, 2c+d] with b,d = {0,1}. Make a table:

    b d | #even
    0 0 | c-a+1
    0 1 | c-a+1
    1 0 | c-a
    1 1 | c-a+1
    

    Now a = min/2, b = min % 2, c = max/2 and d = max % 2.

    So int nEven = max/2 - min/2 + 1 - (min%2).

提交回复
热议问题