Simplest way to calculate amount of even numbers in given range

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

    I'm a bit surprised that iteration was tried to solve this. The minimum number of even numbers possible in a range is equal to half of the length of the array of numbers, or, rangeEnd - rangeStart.
    Add 1 if the first or last number is even.

    So the method is: (using javascript)

    function evenInRange(rangeStart, rangeEnd)
    {
      return
        Math.floor(rangeEnd - rangeStart) + 
        ((rangeStart % 2 == 0) || (rangeEnd % 2 == 0) ? 1 : 0)
    }
    
    
    Tests:
    0 1 2 3 4 5 6 7 8
    8 - 0 = 8
    8 / 2 = 4
    4 + 1 = 5
    Even numbers in range:
    0 2 4 6 8
    
    11 12 13 14 15 16 17 18 19 20
    20 - 11 = 9
    9 / 2 = 4
    4 + 1 = 5
    Even numbers in range
    12 14 16 18 20
    
    1 2 3
    3 - 1 = 2
    2 / 2 = 1
    1 + 0 = 1
    Even numbers in range
    2
    
    2 3 4 5
    5 - 2 = 3
    3 / 2 = 1
    1 + 1 = 2
    Even numbers in range
    2 4
    
    2 3 4 5 6
    6 - 2 = 4
    4 / 2 = 2
    2 + 1 = 3
    Even numbers in range
    2 4 6
    

提交回复
热议问题