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 has 1234 decimal digits and is computed exactly:
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 and , a // n is the floor of and a % n is the remainder, always in , even when 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.
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 without ever building the huge number (it uses square-and-multiply). With exponent it returns the modular inverse, and raises ValueError when none exists.
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
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):
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.
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
intis the same kind of arbitrary-precision integer that cryptography libraries implement in C (OpenSSL'sBIGNUM, GMP'smpz_t, Java'sBigInteger). - 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: , so the quotient is . The remainder then follows from : since , . Always check with the identity , . (In C or JavaScript the quotient would be truncated to and the remainder would be .)
Exercise 2: Last digits of a power (code)
Find the last 6 digits of without computing in full.
Answer
Compute pow(7, 2026, 10**6).
Solution
The last 6 digits are the remainder mod .
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 . Compare int(math.sqrt(N)) with math.isqrt(N).
Answer
isqrt returns exactly ; the float version loses the final 1.
Solution
A double has 53 bits of mantissa, about 16 decimal digits, so is rounded to .
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?
- as a float
- the inverse of modulo , if it exists
In Python, -7 % 3 is…
- -1
- 1
- 2
- an error
Why prefer math.isqrt(n) over int(math.sqrt(n)) for big integers?
- It is shorter
- It is exact; the float version rounds to 53 bits
- It works on strings
- It returns a float