Modulo operation

Learn how to calculate the modulus of a division.

The modulo operation calculates the modulus of a division, which is the rest of the division that cannot be expressed as an exact multiple of the divisor.

To use the modulo operator, place the mod keyword between two numeric values:

/*<operand>*/ mod /*<operand>*/
Try in Playground

You can also use the full name of the operation if you prefer:

/*<operand>*/ modulo /*<operand>*/
Try in Playground

Here is a practical example:

7 mod 3 // 1
Try in Playground

In the above example, the number 7 cannot be completely divided by 3, and there is a remainder of 1.

It is important to emphasize that modulo calculates the modulus and not the remainder. Although they may appear to be the same in many cases, there is a difference when dealing with negative numbers.

Imagine a scenario where you are dividing -7 by 3:

  • The remainder would be -1, as this is the difference between -7 and -6, which is the nearest multiple of 3 that is less than -7.
  • The modulus would be 2, as this is the difference between -7 and -9, which is the nearest multiple of 3 that is greater than -7.

Since CQL uses the modulus definition, the result of the above operation is 2.