Simplest way to calculate amount of even numbers in given range

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

    int start, stop;
    start = 0;
    stop = 9;
    printf("%d",(stop-start)/2+((!(start%2) || !(stop%2)) ? 1 : 0));
    

    Where start and stop can hold any value. No need to iterate to to determine this number.

提交回复
热议问题