The modulus operation finds the remainder when one integer is divided by another. The syntax is typically a % b (read as 'a mod b'), where a is the dividend and b is the divisor.
Example with Positive Number:
29 % 7
1. Divide 29 by 7, quotient = 4 (consider only integer part)
2. Multiply 4 by 7, result = 28
3. Subtract 28 from 29, remainder = 1
Result: 29 % 7 = 1
Example with Negative Number:
-6 % 26
1. Divide -6 by 26, quotient = -1 (consider only integer part)
2. Multiply -1 by 26, result = -26
3. Subtract -26 from -6, remainder = 20
Result: -6 % 26 = 20
Simple trick to perform modulus operation on a negative number:
-32 % 7
Add the divisor (here, 7) to the dividend (here, -32) repeatedly
until you get a positive number.
-32 + 7 = -25
-25 + 7 = -18
-18 + 7 = -11
-11 + 7 = -4
-4 + 7 = 3
When you stop getting negative numbers and obtain the first
positive number, that positive number is the remainder, ie,
the result of the modulus operation.
For your reference, here's the mapping of the alphabets from 0 to 25. Note this down as it will be useful for decoding messages:
| Letter | Index |
|---|---|
| A | 0 |
| B | 1 |
| C | 2 |
| D | 3 |
| E | 4 |
| F | 5 |
| G | 6 |
| H | 7 |
| I | 8 |
| J | 9 |
| K | 10 |
| L | 11 |
| M | 12 |
| N | 13 |
| O | 14 |
| P | 15 |
| Q | 16 |
| R | 17 |
| S | 18 |
| T | 19 |
| U | 20 |
| V | 21 |
| W | 22 |
| X | 23 |
| Y | 24 |
| Z | 25 |