I'm sure that basically every introductory course involves teaching about the ubiquitous mod operation. In my experience, and I'm sure I'm not alone in this, I've found that teaching my students that "mod is the remainder of division" is insufficient if I want them to make any use of the concept later on.
Beyond showing them how to use mod to check divisibility, I have for the last few years gone into far more interesting operations in order to help them achieve some intuitive understanding of what mod is and how it works. So, for instance, I show them how they can increment within a modular circle of numbers from 0
to n-1
(a circle of size n
):
[some loop structure] {
x = (x+1)%n;
}
Or, how to move that circle along so that it ranges from m
to (m+n-1)
(still a circle of size n
, but it no longer starts at 0
):
[some loop structure] {
x = (x+1-m)%n+m;
}
Or how to decrement along a 0
to n-1
circle in a language like Java, which deals with negative modular operations by returning the highest negative congruence (ie. -10 % 4
would return -2
instead of 2
. While they are both technically correct answers, Java's answer is decidedly inconvenient for the purpose of moving along a modular circle of numbers, because when you try to move from 0 back to n-1
, you get the wrong result.)
[some loop structure] {
x = (((x-1)%n)+n)%n;
}
Or, doing the same thing by moving n-1
steps clockwise around the circle instead of moving 1
step counterclockwise:
[some loop structure] {
x = (x+n-1)%n;
}
And, of course, we can generalize this to involve any cyclical pattern of numbers that can be reduced to a proper modular circle where $f(n)$ is the function that takes any number within the cycle to its corresponding location in the modular circle, and $g(n)$ is the function that takes it back:
[some loop structure] {
x = g(f(x+1)%n);
}
Now, I am reasonable certain that nobody uses structures like this in any production environment. Part of my justification for going to such lengths with mod operators has been that I am not a teacher of software engineering. I am a teacher of computer science, and having a firm understanding of modular arithmetic is important for Some Big Ideas later on. (Like Two's Complement, which has a very intuitive and coherent explanation when you think about it in terms of cycles within a number space.) And when all is said and done, many of my students really do come out with a good, intuitive sense of how the mod operation works.
But I also wonder if I have just gone plum crazy. This stuff takes a lot of class time to get the kids to master, and I'm really wondering if the time would be better spent on other pursuits.
How far should modular arithmetic be taken in the CS classes that are early enough along in the curriculum that they still focus on programming?