Why does this condition check the expectation?

38 Views Asked by At

Let's suppose n as an Integer.
Let's suppose i as an Integer.

To check whether the given i is higher than the largest multiple of n that fits in a 32-bit Int, we can do (from a book about programming):

IF(i + (n - 1) - (i % n) < 0) THEN i is higher than the largest multiple of n.

Nothing more is explained in the book.

I don't figure out why this instruction does the job...

1

There are 1 best solutions below

3
On BEST ANSWER

I'd say this is more likely a programming question than a mathematical one. $i + (n-1) - (i \mod n)$ should, under normal circumstances, just return the next multiple of $n$ that comes after $i$. But if that value is larger than the largest possible int, then it will overflow and return a negative value (essentially, this is all wrapped in the implicit modulus operation that occurs when overflows are treated by wrapping values back around).