Maintained by Vikas Dulgunde, software engineer
You are handed two non-negative integers, low and high, with low never larger than high. They mark the two ends of a closed interval, so both endpoints are part of the range you care about.
Your job is to report the count of odd numbers in that interval. An odd number is any integer that leaves a remainder of 1 when divided by 2, such as 1, 3, 5, and 7.
The endpoints can be either parity. low or high might themselves be odd, even, or equal to each other, and any of those should still produce the correct count.
The range can be huge (up to a billion), so walking through every value one at a time is too slow. The answer should come from arithmetic on low and high, not from iterating across the whole interval.
The odd values in [3, 7] are 3, 5, and 7, which is three numbers.
The odds are 1, 3, 5, 7, and 9. The even endpoint 10 contributes nothing.
A single even value sits in the range, so there are no odd numbers at all.
Visible test cases
Counting odds in a wide-open range is hard, but counting odds in [0, n] is a clean closed form. Work out how many odds live in [0, n] for any n.
In [0, n] there are exactly floor((n + 1) / 2) odd numbers. Check it: [0, 7] has 1, 3, 5, 7, which is floor(8 / 2) = 4.
Turn the interval into a difference of two prefixes. Odds in [low, high] equals odds in [0, high] minus odds in [0, low - 1].
Walk every integer from low to high and tally the ones that are odd.
The number of odd values in [0, n] is floor((n + 1) / 2). Subtract the prefix count just below low from the prefix count at high.