Simplest way to calculate amount of even numbers in given range

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

    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
    

提交回复
热议问题