Chapter 14 – Modular Arithmetic and the Multiplicative Cipher 203
Be sure to have the same number of variables as you have values, otherwise Python will raise an
error that says the call needs more or has too many values:
a, b, c = 1, 2
Traceback (most recent call last):
File "<pyshell#8>", line 1, in
a, b, c = 1, 2
ValueError: need more than 2 values to unpack
a, b, c = 1, 2, 3, 4, 5, 6
Traceback (most recent call last):
File "<pyshell#9>", line 1, in
a, b, c = 1, 2, 3, 4, 5, 6
ValueError: too many values to unpack
Swapping Values with the Multiple Assignment Trick
One of the main uses of the multiple assignment trick is to swap the values in two variables. Try
typing the following into the interactive shell:
spam = 'hello'
eggs = 'goodbye'
spam, eggs = eggs, spam
spam
'goodbye'
eggs
'hello'
We will use this swapping trick in our implementation of Euclid’s algorithm.
Euclid’s Algorithm for Finding the GCD of Two Numbers.....................................................................................
Figuring out the GCD of two numbers will be important for doing the multiplicative and affine
ciphers. It seems simple enough: just look at the numbers and write down any factors you can
think of, then compare the lists and find the largest number that is in both of them.
But to program a computer to do it, we’ll need to be more precise. We need an algorithm (that is,
a specific series of steps we execute) to find the GCD of two numbers.
A mathematician who lived 2,000 years ago named Euclid came up with an algorithm for finding
the greatest common divisor of two numbers. Here’s a statue of Euclid at Oxford University: