Skip to content

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 :

ab[n]

The congruence relation may be rewritten as (k ∈ ℤ):

a=b+k×n

More information on Wikipedia.org.

Practical example

123[9]

213[9]

63[9]

Because :

12=3+1×9

21=3+2×9

6=31×9

In python, you can use the % symbol.

>>> 12 % 9 == 21 % 9 == -6 % 9 == 3
True

Addition and substraction

123[9]

You can add or substract any number. Example with +3 and -5 :

156[9]

72[9]

The last equivalence is equals too (sometimes it's easier to deal with positive numbers):

77[9]

Multiplication

123[9]

You can multiply with any number € Z (you cannot make a division, ex: multiply by 1/2).

1. Example with * 3 :

369[9]

Which is equals to :

00[9]

3694=991

2. Example with * -5 :

6015[9]

Which is equals to :

33[9]

60+97=15+29

Divsion (warning)

You can't divise a equivalence relation.

122[10]

Divide by 2 :

61[10]

Modular inverse

The multiplicative inverse :

xa1[n]

xa+nk=1

xa1[n]

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

5×x1[34]

5×x=1+34×k

1=5×734

You can use the modular inverse in Python :

5x1[34]

>>> pow(5, -1, 34)
7
>>> from Crypto.Util.number import inverse
>>> inverse(5, 34)
7
>>> from gmpy2 import invert
>>> invert(5, 34)
mpz(7)