Simplest way to calculate amount of even numbers in given range

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

    In terms of start and length:

    (length >> 1) + (1 & ~start & length)

    half the length plus 1 if start is even and length is odd.

    In terms of start and end:

    ((end - start + 1) >> 1) + (1 & ~start & ~end)

    half the length plus 1 if start is even and end is even.

提交回复
热议问题