简体   繁体   English

在Java中计算范围内偶数数量的最简单方法是什么

[英]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. 例如:如果range为(0,4),则应返回3。

I'm having hard time to think of any simple way. 我很难想到任何简单的方法。 The only solution I came up involved couple of if-statements. 我提出的唯一解决方案涉及几个if语句。 Is there a simple line of code that can do this without if-statements or ternary operator. 是否有简单的代码行可以执行此操作,而无需if语句或三元运算符。

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: 从0到第一个数字的偶数为:

num_evens_first = (first/2 + 1)

The number of evens from 0 to the last number is: 从0到最后一个数字的偶数为:

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. 如果第一个数字本身是偶数,则该范围内的偶数就是这两个数字加1之间的差。 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. 如果范围内的数字数量为偶数,则其中有n / 2个偶数。

If it is odd, you have n / 2 rounded down if first is odd and n / 2 rounded up if first is even. 如果是奇数,你有N / 2向下取整,如果first是奇数和N / 2四舍五入,如果first是偶数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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