Simplest way to calculate amount of even numbers in given range

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

    I'd say

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

    Edit: Erm okay for some reason I thought that (min % 2) returns 1 for even numbers.... :). The correct version is

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

    or rather

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

提交回复
热议问题