简体   繁体   中英

What is the simplest way to calculate the amount of even numbers in a range in java

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 it should return 3.

I'm having hard time to think of any simple way. The only solution I came up involved couple of if-statements. Is there a simple line of code that can do this without if-statements or ternary operator.

public static int countEvens(int first, int last)
{
        int count = 0;
        for(int i = first; i <= last; i++)
        count += i%2 == 0 ? 1 : 0;
        return count;

}

Will this work?

你需要

last / 2 - (first + 1) / 2 + 1

Here is one approach:

The number of evens from 0 to the first number is:

num_evens_first = (first/2 + 1)

The number of evens from 0 to the last number is:

num_evens_last = (last/2 + 1)

The number of evens in the range would be the difference between these two number PLUS 1 if the first number itself is even. Putting this altogether, you can use this formula:

num_evens_last - num_evens_first + (first + 1)%2

Or all at one time:

(last/2 + 1) - (first/2 + 1) + (first + 1)%2

Simplified:

last/2 - first/2 + (first + 1)%2

If the amount of numbers in your range is even, you have n / 2 even numbers in it.

If it is odd, you have n / 2 rounded down if first is odd and n / 2 rounded up if first is even.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM