Modular Arithmetic
Modular arithmetic is a system of arithmetic for integers, which considers the remainder.
In modular arithmetic, numbers "wrap around" upon reaching a given fixed quantity (this given quantity is known as the modulus) to leave a remainder.
Parity
Parity refers to the state of being even or odd.
- Integers have one of two different parities:
- is even means
- is odd means
- Some properties:
- even even = even
- even odd = odd
- odd odd = even
Clock Arithmetic
Time wraps around at 12. In addition, adding any multiple of 12 hours does not change the o'clock.
example 1: now is 10 o'clock. What time is it after 5 hours?
example 2: what time is it after 27 hours from now? What time is it after 39 hours from now?
So a
and b
are the same o'clock if 12 divides a - b
or (a - b) % 12 == 0
const a = 15;
const b = 15 + 12 * 2; // 39
const result = (a - b) % 12;
console.log(result); // 0
Modular Arithmetic
Modular arithmetic is an abstraction of parity and clock arithmetic.
- Parity is arithmetic modulo 2
- Clocks use arithmetic modulo 12
Modular Equivalence
Modular equivalence is also called modular congruence.
Definition: , if is divisible by . Then and are equivalent modulo n.
Example:
Properties of Modular Arithmetic
Modular equivalence plays nicely with ["addition", "subtraction", "multiplication"].
Suppose that and . Then:
This means we can use many tools from normal arithmetic with modular arithmetic.
mod Operator
Definition: is the smallest non-negative integer such that .
Equivalently, is the remainder when you divide by ().
Example: , because
Proof of Lemma
A lemma is little statement that is true in a mathematical theory, derived from its axioms. We can show that it is true by using a proof which shows the steps necessary to get from the axioms to the statement. We can also use other lemmas in the proof if we have already proved them.
Lemma: Let and be integers. .
Proof:
- According to the definition of mod operator, .
- Use modular equivalence definition,
- Based on a well known lemma, we known that , so
Applications of Modular Arithmetic
- Parity
- Clock arithmetic
- RSA encryption
- CPU integer arithmetic
- Indices for ring buffers
Appendix
Code
Vocabulary
Cannot find definitions for "congruence".
Cannot find definitions for "modulo".
Cannot find definitions for "axioms".