Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 整数运算:在UINT_MAX上加1,然后除以n而不溢出_C_Integer Overflow_Integer Division - Fatal编程技术网

C 整数运算:在UINT_MAX上加1,然后除以n而不溢出

C 整数运算:在UINT_MAX上加1,然后除以n而不溢出,c,integer-overflow,integer-division,C,Integer Overflow,Integer Division,有没有办法计算((UINT_MAX+1)/x)*x-1 在C语言中,不使用unsigned long(其中x是unsigned int)? (根据体系结构,相应的“无需诉诸无符号long”)sizeof(无符号long)==sizeof(无符号int)==4在大多数现代编译器上。您可能希望使用无符号long-long。对于整数除法,我们具有以下等价性 (y/x)*x == y - y%x (UINT_MAX+1)%x == ((UINT_MAX % x) +1)%x 所以我们有 ((UINT

有没有办法计算
((UINT_MAX+1)/x)*x-1
在C语言中,不使用
unsigned long
(其中
x
unsigned int
)?
(根据体系结构,相应的“无需诉诸
无符号long
”)

sizeof(无符号long)==sizeof(无符号int)==4在大多数现代编译器上。您可能希望使用无符号long-long。

对于整数除法,我们具有以下等价性

(y/x)*x == y - y%x
(UINT_MAX+1)%x == ((UINT_MAX % x) +1)%x
所以我们有

((UINT_MAX+1)/x)*x-1 == UINT_MAX - (UINT_MAX+1)%x
将此结果与以下等价性相结合

(y/x)*x == y - y%x
(UINT_MAX+1)%x == ((UINT_MAX % x) +1)%x
我们得到

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

可使用
无符号int
进行计算

这是一个相当简单的算法:

((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)

你为什么要这样做?你的x是不是碰巧是2的幂?这是在a
无符号int
递减1的范围内x的最大倍数。你的表达式简化为UINT_MAX,除非你忘记添加一些括号。在C中:当整数被除时,/运算符的结果是代数商,任何小数部分都被丢弃。“这个问题要求不要使用
无符号long
。我比我给出的答案更喜欢这个答案。x不能大于UINT\u MAX。@谢谢你指出这一点。我没有仔细阅读这个问题,认为x的类型是unsignedlong,而不是unsignedint。