简体   繁体   English

整数算术:将1加到UINT_MAX并除以n而不溢出

[英]Integer arithmetic: Add 1 to UINT_MAX and divide by n without overflow

Is there a way to compute the result of ((UINT_MAX+1)/x)*x-1 in C without resorting to unsigned long (where x is unsigned int )? 有没有办法在C中计算((UINT_MAX+1)/x)*x-1的结果而不求助于unsigned long (其中xunsigned int )? (respective "without resorting to unsigned long long " depending on architecture.) (根据架构,各自“不使用unsigned long long ”。)

It is rather simple arithmetic: 这是一个相当简单的算术:

((UINT_MAX + 1) / x) * x - 1 =
((UINT_MAX - x + x + 1) / x) * x - 1 = 
((UINT_MAX - x + 1) / x + 1) * x - 1 =
(UINT_MAX - x + 1) / x) * x + (x - 1)

With integer divisions we have the following equivalence 对于整数除法,我们有以下等价

(y/x)*x == y - y%x

So we have 所以我们有

((UINT_MAX+1)/x)*x-1 == UINT_MAX - (UINT_MAX+1)%x

combining this result with the following equivalence 将此结果与以下等效性相结合

(UINT_MAX+1)%x == ((UINT_MAX % x) +1)%x

we get 我们得到

((UINT_MAX+1)/x)*x-1 == UINT_MAX - ((UINT_MAX % x) +1)%x

which is computable with an unsigned int . 这可以用unsigned int

sizeof(unsigned long) == sizeof(unsigned int) == 4 on most modern compilers. 大多数现代编译器的sizeof(unsigned long)== sizeof(unsigned int)== 4。 You might want to use use unsigned long long. 您可能希望使用unsigned long long。

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

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