r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

8

u/Patrickstarho Apr 05 '22

Ceaser Cipher. I get your supposed to shift each character by n but the whole modulus thing makes no sense to me. I remember I did the problem and wrote it out 10 times. 2 weeks later I was stuck again

1

u/AlSweigart Author: ATBS Apr 05 '22 edited Apr 05 '22

So Caesar Cipher works by shifting letters over by 3 spaces in the alphabet (A to D, B to E, etc) and then decrypts by shifting lettes back by 3 spaces (D to A, E to B, etc).

This sort of math is easier to do with numbers than letters, so we set up numbers for each letter: A is 0, B is 1, all the way up to Z is 25. (There are 26 letters, but Z is 25 because we start at 0 for A.) To "shift", we add 3: A is 0, and 0 + 3 is 3, and 3 is D. So when we encrypt the letter A it becomes D.

To decrypt and shift the letters back, we subtract: D is 3, and 3 - 3 is 0, and 0 is A.

The problem comes at the beginning and end of the alphabet. X is 23, 23 + 3 is 26, but there is no 26th letter of the alphabet (when we start A as the 0th letter). So instead we need some mathematical way to "wrap around" 26 to be 0, so that X encrypts to A. Same at the beginning: A is 0, 0 - 3 is -3 which is smaller than 0 (the first letter's number).

Here's where mod comes in. People commonly think of mod as "the remainder" of divison: 23 divided by 3 is 7 remainder 2, so 23 mod 3 is 2. (This is exactly what modulus is, but close enough for Caesar Cipher.)

Here's a little pattern to notice. At the top is a series of integers n, and below is n mod 4

0 1 2 3 4 5 6 7 8 9 10 11 12 13
0 1 2 3 0 1 2 3 0 1 2  3  0  1

Notice we get this "wrap around" pattern of 0 to 3 in order. We can use mod to wrap around our numbers that stand for letters:

26 mod 26 = 0, so X is 23, and 23 + 3 is 26, and 26 mod 26 is 0, and 0 is A, so X decrypts to A.

This also works on the other end:

-3 mod 26 = 23, so since A is 0, and 0 - 3 is -3, and -3 mod 26 is 23, and 23 is X, so A decrypts to X.

Meanwhile, it still works with all the other letters:

Encrypting A has A is 0, 0 + 3 = 3, and 3 mod 26 is 3, and 3 is D, so A encrypts to D.

Of course, we don't need mod for Caesar Cipher. It'd be easy enough to say "if the encrypted number is greater than 25, subtract 26" and "if the decrypted number is less than 0, add 26". But this is basically what mod is doing for us.