TExcelTAD
Home › Number Theory & Cryptography › Number Theory with Python

Number Theory with Python

Python is an unusually good calculator for number theory: its integers never overflow, the three-argument pow does modular exponentiation in microseconds, and the math module has gcd, lcm and an exact integer square root. This lesson is a tour of the tools used in every later lesson.

Big integers

A Python int grows as needed. The number 240962^{4096} has 1234 decimal digits and is computed exactly:

python · try it yourself
x = 2 ** 4096
print(len(str(x)), "digits,", x.bit_length(), "bits")
print("last 10 digits:", x % 10**10)
print(int("123456789" * 5) * 987654321 % 1000003)
1234 digits, 4097 bits
last 10 digits: 3154190336
118601

Quotient and remainder

For integers aa and n>0n > 0, a // n is the floor of a/na / n and a % n is the remainder, always in {0,1,…,n−1}\{0, 1, \ldots, n - 1\}, even when aa is negative. divmod returns both. This matches the mathematical convention of the Division Algorithm; C, Java and JavaScript instead truncate toward zero, so -7 % 3 is -1 there and 2 in Python.

python · try it yourself
for a in (17, -17):
    q, r = divmod(a, 5)
    print(f"{a} = 5*{q} + {r}")
print("-7 % 3 =", -7 % 3)
17 = 5*3 + 2
-17 = 5*-4 + 3
-7 % 3 = 2

The three-argument pow

pow(a, e, n) computes ae mod na^e \bmod n without ever building the huge number aea^e (it uses square-and-multiply). With exponent −1-1 it returns the modular inverse, and raises ValueError when none exists.

python · try it yourself
p = 10**9 + 7
print(pow(3, 10**18, p))
print(pow(10, -1, 17), (10 * pow(10, -1, 17)) % 17)
try:
    pow(6, -1, 9)
except ValueError as err:
    print("no inverse:", err)
246336683
12 1
no inverse: base is not invertible for the given modulus

The math module

python · try it yourself
import math

print(math.gcd(84, 120), math.lcm(84, 120))
print(math.isqrt(10**20 + 12345))           # floor of the square root, exact
print(math.comb(50, 3), math.prod([2, 3, 5, 7]))
12 840
10000000000
19600 210

math.isqrt matters because math.sqrt goes through a float with 53 bits of precision; for a 100-digit integer it returns a wrong answer, while isqrt is always exact.

Bytes and integers

Cryptography works on byte strings, number theory on integers. int.from_bytes and int.to_bytes convert between them (big-endian is the usual convention, as in RSA's I2OSP/OS2IP primitives):

python · try it yourself
m = int.from_bytes(b"Hi!", "big")
print(m, hex(m))
print(m.to_bytes(3, "big"))
4745505 0x486921
b'Hi!'

Checking your work

SymPy, available in the playground, has trustworthy reference implementations: sympy.isprime, sympy.factorint, sympy.totient, sympy.ntheory.residue_ntheory. Lessons implement each algorithm by hand, then compare with SymPy.

python · try it yourself
from sympy import factorint, isprime, totient

print(factorint(360), isprime(2**61 - 1), totient(360))
{2: 3, 3: 2, 5: 1} True 96

In software

  • Python's int is the same kind of arbitrary-precision integer that cryptography libraries implement in C (OpenSSL's BIGNUM, GMP's mpz_t, Java's BigInteger).
  • Production code never uses pow(m, d, n) for private keys: the running time depends on the secret exponent. Libraries use constant-time ladders and blinding.

Exercises

Exercise 1: Negative remainders

What do -23 % 7 and -23 // 7 return in Python, and why?

Answer

5 and -4.

Solution

Python's // rounds down: −23/7≈−3.29-23/7 \approx -3.29, so the quotient is −4-4. The remainder then follows from −23=7⋅(−4)+r-23 = 7 \cdot (-4) + r: since 7⋅(−4)=−287 \cdot (-4) = -28, r=−23+28=5r = -23 + 28 = 5. Always check with the identity a=nq+ra = nq + r, 0≤r<n0 \le r < n. (In C or JavaScript the quotient would be truncated to −3-3 and the remainder would be −2-2.)

Exercise 2: Last digits of a power (code)

Find the last 6 digits of 720267^{2026} without computing 720267^{2026} in full.

Answer

Compute pow(7, 2026, 10**6).

Solution

The last 6 digits are the remainder mod 10610^6.

python · try it yourself
print(pow(7, 2026, 10**6), str(7**2026)[-6:])
105649 105649

Both ways agree; the three-argument form stays fast even for exponents with thousands of digits.

Exercise 3: float versus isqrt (code)

Let N=(1020+1)2N = (10^{20} + 1)^2. Compare int(math.sqrt(N)) with math.isqrt(N).

Answer

isqrt returns exactly 1020+110^{20} + 1; the float version loses the final 1.

Solution

A double has 53 bits of mantissa, about 16 decimal digits, so 1020+110^{20} + 1 is rounded to 102010^{20}.

python · try it yourself
import math
N = (10**20 + 1) ** 2
print(int(math.sqrt(N)), math.isqrt(N))
100000000000000000000 100000000000000000001

Test yourself

What does pow(a, -1, n) compute?

  1. 1/a1/a as a float
  2. the inverse of aa modulo nn, if it exists
  3. an−1a^{n-1}
  4. −a mod n-a \bmod n

In Python, -7 % 3 is…

  1. -1
  2. 1
  3. 2
  4. an error

Why prefer math.isqrt(n) over int(math.sqrt(n)) for big integers?

  1. It is shorter
  2. It is exact; the float version rounds to 53 bits
  3. It works on strings
  4. It returns a float