Introduction
Congruence
Congruence modulo n
is a congruence relation, meaning that it is an equivalence relation that is compatible with the operations of addition, subtraction, and multiplication. Congruence modulo n
is denoted :
The congruence relation may be rewritten as (k ∈ ℤ):
More information on Wikipedia.org.
Practical example
Because :
In python, you can use the %
symbol.
>>> 12 % 9 == 21 % 9 == -6 % 9 == 3
True
Addition and substraction
You can add or substract any number. Example with +3
and -5
:
The last equivalence is equals too (sometimes it's easier to deal with positive numbers):
Multiplication
You can multiply with any number € Z (you cannot make a division, ex: multiply by 1/2
).
1. Example with * 3
:
Which is equals to :
2. Example with * -5
:
Which is equals to :
Divsion (warning)
You can't divise a equivalence relation.
Divide by 2
:
Modular inverse
The multiplicative inverse :
It may be efficiently computed by solving Bézout's equation a * x + n * k = 1
using the Extended Euclidean algorithm (used to compute the GCD - Greatest common divisor).
Practical example
You can use the modular inverse in Python :
>>> pow(5, -1, 34)
7
>>> from Crypto.Util.number import inverse
>>> inverse(5, 34)
7
>>> from gmpy2 import invert
>>> invert(5, 34)
mpz(7)