The Grinnell Scheme Web: The modulo
procedure

What does the modulo procedure do?

It's almost a clone of the remainder procedure. If the first operand is an exact multiple of the second, or if they have the same sign, modulo works exactly like remainder and returns the same value.

However, the idea behind the procedure is a little bit different. Suppose that you have a positive integer n, and you want to partition the set of all integers into n subsets on the basis of how they are related to multiples of n. The multiples of n themselves will form one subset, {..., -3n, -2n, -n, 0, n, 2n, 3n, ...}. The integers that are one unit greeater than multiples of n will form another subset, {..., -3n + 1, -2n + 1, -n + 1, 1, n + 1, 2n + 1, 3n + 1, ...}. The integers that are two units greater than multiples of n will form yet another subset, and so on. Finally, there will be a subset containing integers that are n - 1 units greater than multiples of n: {..., -2n - 1, -n - 1, -1, n - 1, 2n - 1, 3n - 1, 4n - 1, ...}. In mathematics, these subsets are called equivalence classes modulo n.

The modulo procedure examines the first operand and determines which of the equivalence classes modulo n it belongs to (where n is the second operand). It then returns the ``principal value'' of that equivalence class, which is the one that lies in the range from 0 (inclusive) to n (exclusive):

> (modulo 45 6)
3
> (modulo 12 6)
0
> (modulo -1 6)
5
> (modulo -6 6)
0
> (modulo -17 6)
1
What happens if the second operand is negative, then?

Then the modulo procedure returns a different ``principal value'' -- one that lies in the range from n (exclusive) to 0 (inclusive):

> (modulo 45 -6)
-3
> (modulo 12 -6)
0
> (modulo -1 -6)
-1
> (modulo -17 -6)
-5
The general rule is that the value returned by modulo, if it is not zero, has the same sign as the second operand (the modulus).

In the C programming language, there is a % operation on integers. Does it correspond to remainder or to modulo?

When C's % operation gets a negative operand, its behavior depends on the instruction set of the central processing unit of the computer on which the operation is performed. Usually, though not always, it works like remainder. Scheme's procedures are more precisely defined.

What about Pascal's mod operation -- is it like remainder or modulo?

The Pascal standard says that it works like modulo, except that in Pascal it's an error for the second operand to be negative. On the other hand, you may have learned Turbo Pascal. Turbo Pascal's mod operation works like remainder. Go figure.


Next topic
Previous topic
Table of contents


This document is available on the World Wide Web as

http://www.math.grin.edu/~stone/scheme-web/modulo.html


created June 24, 1995
last revised December 29, 1995

Copyright 1995 by John David Stone (stone@math.grin.edu)