Simplest way to calculate amount of even numbers in given range

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

    int even = (0 == begin % 2) ? (end - begin) / 2 + 1 : (end - begin + 1) / 2;
    

    Which can be converted into:

    int even = (end - begin + (begin % 2)) / 2 + (1 - (begin % 2));
    

    EDIT: This can further simplified into:

    int even = (end - begin + 2 - (begin % 2)) / 2;
    

    EDIT2: Because of the in my opinion somewhat incorrect definition of integer division in C (integer division truncates downwards for positive numbers and upwards for negative numbers) this formula won't work when begin is a negative odd number.

    EDIT3: User 'iPhone beginner' correctly observes that if begin % 2 is replaced with begin & 1 this will work correctly for all ranges.

提交回复
热议问题