Chapter 14 – Modular Arithmetic and the Multiplicative Cipher 199
The % Mod Operator
This sort of “wrap-around” arithmetic is called modular arithmetic. We say “fifteen mod
twelve” is equal to 3. (Just like how “15 o’clock” mod twelve would be “3 o’clock.) In Python,
the mod operator is the % percent sign. Try typing the following into the interactive shell:
15 % 12
3
210 % 12
6
10 % 10
0
20 % 10
0
“Mod” is “Division Remainder”(Sort Of)
You can think of the mod operator as a “division remainder” operator. 21 ÷ 5 = 4 remainder 1.
And 21 % 5 = 1. This works pretty well for positive numbers, but not for negative numbers. - 21 ÷
5 = -4 remainder -1. But the result of a mod operation will never be negative. Instead, think of
that -1 remainder as being the same as 5 – 1, which comes to 4. This is exactly what -21 % 5
evaluates to:
-21 % 5
4
But for the purposes of cryptography in this book, we’ll only be modding positive numbers.
Practice Exercises, Chapter 14, Set A
Practice exercises can be found at http://invpy.com/hackingpractice 14 A.
GCD: Greatest Common Divisor (aka Greatest Common Factor)
Factors are the numbers that can be multiplied to produce a particular number. Look at this
simple multiplication:
4 × 6 = 24
In the above math problem, we say 4 and 6 are factors of 24. (Another name for factor is
divisor.) The number 24 also has some other factors: