TExcelTAD
Home › Number Theory & Cryptography › Solving Linear Congruences

Solving Linear Congruences

A linear congruence ax≡b(modn)ax \equiv b \pmod{n} is the modular version of ax=bax = b. It may have no solution, exactly one, or several, and the gcd decides which. Affine ciphers, linear congruential generators and hash-function analysis all come down to solving one.

The rule

Let g=gcd⁡(a,n)g = \gcd(a, n).

  • If g∤bg \nmid b, there is no solution.
  • If g∣bg \mid b, there are exactly gg solutions modulo nn. Divide through by gg: agx≡bg(modng)\frac{a}{g} x \equiv \frac{b}{g} \pmod{\frac{n}{g}} has the unique solution x0=bg(ag)−1 mod ngx_0 = \frac{b}{g} \left(\frac{a}{g}\right)^{-1} \bmod \frac{n}{g}, and the solutions modulo nn are x0,x0+ng,…,x0+(g−1)ngx_0, x_0 + \frac{n}{g}, \ldots, x_0 + (g - 1)\frac{n}{g}.

This is the linear Diophantine equation ax−ny=bax - ny = b in another notation.

python · try it yourself
from math import gcd

def solve_linear(a, b, n):
    g = gcd(a, n)
    if b % g:
        return []
    a2, b2, n2 = a // g, b // g, n // g
    x0 = b2 * pow(a2, -1, n2) % n2 if n2 > 1 else 0
    return [x0 + k * n2 for k in range(g)]

print(solve_linear(7, 3, 10))      # g = 1: one solution
print(solve_linear(6, 4, 10))      # g = 2: two solutions
print(solve_linear(6, 5, 10))      # g = 2 does not divide 5: none
print(solve_linear(12, 18, 30))
[9]
[4, 9]
[]
[4, 9, 14, 19, 24, 29]

Check one: 7⋅9=63≡3(mod10)7 \cdot 9 = 63 \equiv 3 \pmod{10}.

The affine cipher

A classic toy cipher maps letter x∈{0,…,25}x \in \{0, \ldots, 25\} to ax+b mod 26ax + b \bmod 26. Decryption solves the linear congruence: x≡a−1(y−b)x \equiv a^{-1}(y - b). It only works when gcd⁡(a,26)=1\gcd(a, 26) = 1, so 12 values of aa are usable.

python · try it yourself
from math import gcd

def affine(text, a, b, decrypt=False):
    out = []
    for ch in text:
        x = ord(ch) - 65
        y = (pow(a, -1, 26) * (x - b)) % 26 if decrypt else (a * x + b) % 26
        out.append(chr(y + 65))
    return "".join(out)

c = affine("MODULARARITHMETIC", 5, 8)
print(c, affine(c, 5, 8, decrypt=True))
print("valid a:", [a for a in range(26) if gcd(a, 26) == 1])
QAXELIPIPWZRQCZWS MODULARARITHMETIC
valid a: [1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25]

With only 12⋅26=31212 \cdot 26 = 312 keys, it falls to brute force or to two known letter pairs (two linear congruences in aa and bb). It is a teaching example of the arithmetic, not a cipher.

Linear congruential generators

The old random-number generator xk+1=(axk+c) mod mx_{k+1} = (a x_k + c) \bmod m is a linear congruence too. Given three consecutive outputs and mm, you can solve for aa and cc and predict every later value: one reason LCGs must never be used for security (Secure Random Numbers).

python · try it yourself
m, a, c = 2**31, 1103515245, 12345      # a classic C library LCG
xs = [42]
for _ in range(4):
    xs.append((a * xs[-1] + c) % m)

# attacker sees xs[0], xs[1], xs[2]; solve a*(x1 - x0) = x2 - x1 (mod m)
d1, d2 = xs[1] - xs[0], xs[2] - xs[1]
from math import gcd
g = gcd(d1, m)
cands = [(d2 // g) * pow(d1 // g, -1, m // g) % (m // g) + k * (m // g) for k in range(g)] if d2 % g == 0 else []
for a_guess in cands:
    c_guess = (xs[1] - a_guess * xs[0]) % m
    pred = (a_guess * xs[2] + c_guess) % m
    print("a, c =", a_guess, c_guess, " predicted next:", pred, " actual:", xs[3])
a, c = 1103515245 12345  predicted next: 1000676753  actual: 1000676753

In software

  • java.util.Random, older rand() implementations and many game engines use LCGs: fine for shuffling a level, broken as soon as an adversary sees outputs.
  • Compilers turn division by a constant into multiplication by a modular inverse when the division is known to be exact (for example pointer differences divided by the element size).

Exercises

Exercise 1: Count the solutions

How many solutions modulo 24 do these have: (a) 9x≡69x \equiv 6; (b) 9x≡59x \equiv 5; (c) 5x≡75x \equiv 7?

Answer

(a) 3, (b) 0, (c) 1.

Solution

gcd⁡(9,24)=3\gcd(9, 24) = 3 divides 6 but not 5. gcd⁡(5,24)=1\gcd(5, 24) = 1, so (c) has exactly one solution.

Exercise 2: Solve by hand

Solve 9x≡6(mod24)9x \equiv 6 \pmod{24}.

Answer

x≡6,14,22(mod24)x \equiv 6, 14, 22 \pmod{24}.

Solution

Divide by 3: 3x≡2(mod8)3x \equiv 2 \pmod 8. The inverse of 3 modulo 8 is 3 (9≡19 \equiv 1), so x≡6(mod8)x \equiv 6 \pmod 8. Modulo 24: 6,14,226, 14, 22. Check: 9⋅14=126=5⋅24+69 \cdot 14 = 126 = 5 \cdot 24 + 6.

Exercise 3: Break an affine cipher (code)

An affine cipher maps E to R and T to W (letters numbered A = 0). Find aa and bb.

Answer

a=9a = 9, b=7b = 7.

Solution

E = 4 maps to R = 17 and T = 19 maps to W = 22: 4a+b≡174a + b \equiv 17 and 19a+b≡22(mod26)19a + b \equiv 22 \pmod{26}. Subtracting gives 15a≡5(mod26)15a \equiv 5 \pmod{26}. Since 15⋅7=105≡115 \cdot 7 = 105 \equiv 1, 15−1≡715^{-1} \equiv 7 and a≡35≡9a \equiv 35 \equiv 9; then b≡17−36≡7b \equiv 17 - 36 \equiv 7.

python · try it yourself
a = 5 * pow(15, -1, 26) % 26
b = (17 - 4 * a) % 26
print(a, b, (4 * a + b) % 26, (19 * a + b) % 26)
9 7 17 22

Test yourself

How many solutions does ax≡b(modn)ax \equiv b \pmod{n} have when g=gcd⁡(a,n)g = \gcd(a, n) divides bb?

  1. exactly 1
  2. exactly gg modulo nn
  3. nn
  4. none

An affine cipher x↦ax+b mod 26x \mapsto ax + b \bmod 26 can be decrypted only if…

  1. aa is even
  2. gcd⁡(a,26)=1\gcd(a, 26) = 1
  3. b=0b = 0
  4. a=ba = b

Why are linear congruential generators unsafe for cryptography?

  1. they are slow
  2. a few outputs let you solve for the parameters and predict the rest
  3. they need a prime modulus
  4. they never repeat