Simplest way to calculate amount of even numbers in given range

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

    Let's look at this logically ...

    We have four cases ...

    odd -> odd     eg.  1 -> 3  answer: 1
    odd -> even    eg.  1 -> 4  answer: 2
    even -> odd    eg.  0 -> 3  answer: 2
    even -> even   eg.  0 -> 4  answer: 3
    

    The first three cases can be handled simply as ...

    (1 + last - first) / 2
    

    The fourth case does not fall quite so nicely into this, but we can fudge around a little bit for it quite easily ...

    answer = (1 + last - first) / 2;
    if (both first and last are even)
        answer++;
    

    Hope this helps.

提交回复
热议问题