user3079090
user3079090

Reputation: 13

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?

Upvotes: 0

Views: 129

Answers (3)

David Fleeman
David Fleeman

Reputation: 2638

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

Upvotes: 2

Blub
Blub

Reputation: 3822

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.

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79848

You need

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

Upvotes: 3

Related Questions