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.)
Asked
Active
Viewed 251 times
1

Moritz Schauer
- 1,378
- 9
- 19
-
1Why are you trying to do this? – Ed Heal Mar 21 '15 at 11:17
-
Is your x, by chance, a power of 2 ? – manasij7479 Mar 21 '15 at 11:19
-
1This is the maximum multiple of x within the range of a `unsigned int` decremented by one. – Moritz Schauer Mar 21 '15 at 11:45
-
Your expression simplifies to UINT_MAX, unless you forgot to add some parenthesis. – reader Mar 21 '15 at 13:07
-
2In C: "When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded." – Moritz Schauer Mar 21 '15 at 13:22
-
related: [How to compute 2⁶⁴/n in C?](https://stackoverflow.com/q/55565537/995714) – phuclv Apr 09 '19 at 14:08
3 Answers
4
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)

vharavy
- 4,881
- 23
- 30
-
-
2
-
@chmike Thanks for pointing that out. I did not read the question carefully and thought that x is of type unsigned long rather than unsigned int. – vharavy Mar 21 '15 at 16:21
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
.

chmike
- 20,922
- 21
- 83
- 106
-2
sizeof(unsigned long) == sizeof(unsigned int) == 4 on most modern compilers. You might want to use use unsigned long long.

wik146
- 1