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\
This'll do the trick, even for ranges with negative numbers.
int even = (last - first + 2 - Math.abs(first % 2) - Math.abs(last % 2)) / 2;
Tested with the following code:
public static void main(String[] args) {
int[][] numbers = {{0, 4}, {0, 5}, {1, 4}, {1, 5}, {4, 4}, {5, 5},
{-1, 0}, {-5, 0}, {-4, 5}, {-5, 5}, {-4, -4}, {-5, -5}};
for (int[] pair : numbers) {
int first = pair[0];
int last = pair[1];
int even = (last - first + 2 - Math.abs(first % 2) - Math.abs(last % 2)) / 2;
System.out.println("[" + first + ", " + last + "] -> " + even);
}
}
Output:
[0, 4] -> 3
[0, 5] -> 3
[1, 4] -> 2
[1, 5] -> 2
[4, 4] -> 1
[5, 5] -> 0
[-1, 0] -> 1
[-5, 0] -> 3
[-4, 5] -> 5
[-5, 5] -> 5
[-4, -4] -> 1
[-5, -5] -> 0