The remainder / modulus operator (`%`

) returns the remainder after (integer) division.

This operator returns the remainder left over when one operand is divided by a second operand. When the first operand is a negative value, the return value will always be negative, and vice versa for positive values.

In the example above, `10`

can be subtracted four times from `42`

before there is not enough left to subtract again without it changing sign. The remainder is thus: `42 - 4 * 10 = 2`

.

The remainder operator may be useful for the following problems:

1. Test if an integer is (not) divisible by another number:

Since `0 === -0`

, this also works for `x <= -0`

.

2. Implement cyclic increment/decrement of value within `[0, n)`

interval.

Suppose that we need to increment integer value from `0`

to (but not including) `n`

, so the next value after `n-1`

become `0`

. This can be done by such pseudocode:

Now generalize the above problem and suppose that we need to allow to both increment and decrement that value from `0`

to (not including) `n`

, so the next value after `n-1`

become `0`

and the previous value before `0`

become `n-1`

.

Now we can call `delta()`

function passing any integer, both positive and negative, as delta parameter.

## Leave a Reply