Simplest way to calculate amount of even numbers in given range

前端 未结 16 2433
小蘑菇
小蘑菇 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.

    0 讨论(0)
  • 2021-02-13 15:01

    The count of even numbers between 0 and n is [n/2] + 1. Therefore the count of even numbers between (n + 1) and m is ([m/2] + 1) - ([n/2] + 1) = [m/2] - [n/2].

    For count of even numbers between m and n the answer therefore would be [m/2] - [(n - 1)/2].

    The [x] is taken to the direction of -\infty. Beware that the usual C integer division is not doing right in our case: a/2 is rounded towards zero, not -\infty, so the result will be not [a/2] for teh case of negative a.

    This should be the simplest calculation; works for negative numbers, too. (Needs however that m >= n.) Doesn't contain ifs and ?:s.

    If you don't consider negative numbers, you can use just m/2 - (n+1)/2 + 1, otherwise floor(m/2.0) - floor((n-1)/2.0)

    0 讨论(0)
  • 2021-02-13 15:02

    Pseudo code (i'm no C coder):

    count = 0;
    foreach(i in range){
        if(i % 2 == 0){
          count++;
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题