|
|
|
|
|
by bertr4nd
2066 days ago
|
|
First it's important to note that `n` is unsigned; if it's signed the value of `-n % n` is 0, intuitively. For unsigned n, the value is: MAX - n + 1 (where max is the maximum representable value in the type of n, e.g., UINT_MAX). The article explains this nicely. (I thought of 2's complement when reasoning through this, but you don't actually need to assume 2's complement to follow the reasoning). So, `-n % n` computes `(MAX - n + 1) % n` efficiently, without needing to worry about corner cases. I suspect this is useful when you want to generate random numbers with a limited range, where the range doesn't cleanly divide UINT_MAX. You need to cut a bit off the top from your underlying random number generator. |
|
It's calculating ((-n) mod (2^bits)) mod n, where bits is compiler/platform-dependent.
I would not use this, except possibly with a precise-width type like uint32_t.