计算在给定范围内偶数量的最简单方法 [英] Simplest way to calculate amount of even numbers in given range
问题描述
什么是计算在一个范围内的无符号整数的偶数量最简单的方法?
一个例子:如果范围是[0 ... 4]那么答案是3(0,2,4)
我有时间难以想到的任何简单的方法。唯一的解决方案,我想出了几个参与if语句的。有code的简单的线条,可以做到这一点没有if语句或三元操作?
诠释甚至=(0 ==开始%2)? (结束 - 开始)/ 2 + 1:(结束 - 开始+ 1)/ 2;
哪些可转换成:
INT即使=(结束 - 开始+(开头%2))/ 2 +(1 - (开头%2));
编辑:可以进一步简化为:
INT即使=(结束 - 开始+ 2 - (开头%2))/ 2;
EDIT2:由于对在我看来,用C整数除法有点不正确定义(整数除法向下截断为正数,向上为负数)时开始这个公式将无法工作是一个负奇数。
EDIT3:用户iPhone初学者正确地指出,如果开始%2
替换开始&安培; 1
这将正常工作的所有范围。
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'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 operators?
int even = (0 == begin % 2) ? (end - begin) / 2 + 1 : (end - begin + 1) / 2;
Which can be converted into:
int even = (end - begin + (begin % 2)) / 2 + (1 - (begin % 2));
EDIT: This can further simplified into:
int even = (end - begin + 2 - (begin % 2)) / 2;
EDIT2: Because of the in my opinion somewhat incorrect definition of integer division in C (integer division truncates downwards for positive numbers and upwards for negative numbers) this formula won't work when begin is a negative odd number.
EDIT3: User 'iPhone beginner' correctly observes that if begin % 2
is replaced with begin & 1
this will work correctly for all ranges.
这篇关于计算在给定范围内偶数量的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!