Simplest way to calculate amount of even numbers in given range

前端 未结 16 2444
小蘑菇
小蘑菇 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 15:05

    The answer:

    (max - min + 2 - (max % 2) - (min % 2)) / 2
    

    A short explanation:

    • even..even yields (length + 1) / 2
    • even..odd yields length / 2
    • odd..even yields length / 2
    • odd..odd yields (length - 1) / 2

    • length = max - min + 1

    Therefore, the answer is (length - 1) / 2 plus 1/2 for even min plus 1/2 for even max. Note that (length - 1) / 2 == (max - min) / 2, and the "bonuses" are (1 - (min % 2)) / 2 and (1 - (max % 2)) / 2. Sum this all up and simplify to obtain the answer above.

提交回复
热议问题