问题
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