1

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

Moritz Schauer
  • 1,378
  • 9
  • 19

3 Answers3

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