Modulus and Remainder


mod - (modulus)

% - (remainder)


The remainder operator (%) and the modulus operator (mod) perform very similar functions and can easily be confused.

Given two positive numbers, a (the dividend) and n (the divisor), (a % n) can be thought of as the remainder. For instance, the expression (7 % 3) would evaluate to 1 because after dividing 7 by 3 the subtraction of 6 from 7 leaves 1, while (9 % 3) would evaluate to 0 because the division of 9 by 3 is even, there is nothing to subtract from 9 after multiplying 3 times 3.

When a and n are both positive the remainder operator (%) and the modulus operator (mod) work exactly the same.


When either a or n are negative, this definition breaks down and many programming languages differ in how these values are defined. Basic provides both the remainder operand (%) and the modulus operand (mod) to handle both ways of dealing with this situation.


The % operator is defined as:

(a % n) = (a - (n * int(a/n)))

Therefore

(-9 % 7) = (-9 - (7 * -1)) = -2


The mod operator is defined as:

(a mod n) = (a - (n * floor(a/n)))

Therefore

(-9 mod 7) = (-9 - (7 * -2)) = 5






Become a Patron