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

百般思念 提交于 2019-12-13 02:24:41

问题


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)? (respective "without resorting to unsigned long long" depending on architecture.)


回答1:


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)



回答2:


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.




回答3:


sizeof(unsigned long) == sizeof(unsigned int) == 4 on most modern compilers. You might want to use use unsigned long long.



来源:https://stackoverflow.com/questions/29182036/integer-arithmetic-add-1-to-uint-max-and-divide-by-n-without-overflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!