Sub topic 5
Integer math: factorial, comb, perm, gcd, and isqrt
This chapter assumes you can call functions from an imported module and know the difference between int and float. The math module also has functions that work only on whole numbers. They return exact int results, however large, and they don't suffer the rounding problems that floats do.
Factorials and counting
math.factorial(n) returns n! (n × (n−1) × … × 1) as an exact integer. Two other functions answer the usual counting questions:
math.perm(n, k)counts ordered selections ofkitems fromn. Order matters, so "A then B" differs from "B then A".math.comb(n, k)counts unordered selections. Order does not matter, so "A and B" is one choice.
import math
print(math.factorial(5)) # 120
print(math.perm(5, 2)) # 20
print(math.comb(5, 2)) # 10
print(math.comb(52, 5)) # 2598960 possible five-card poker hands
print(math.comb(2, 5)) # 0, because you can't pick 5 items from 2perm is always comb multiplied by factorial(k). In the example, 10 × 2 = 20, because each pair can be arranged in two orders.
These functions compute the result directly, without building a huge factorial first. Prefer math.comb(52, 5) to factorial(52) // (factorial(5) * factorial(47)), which is slower and longer.
Greatest common divisor and least common multiple
math.gcd returns the largest integer that divides all its arguments. math.lcm (Python 3.9 and later) returns the smallest positive integer that all of them divide. Both accept more than two arguments.
import math
print(math.gcd(12, 18)) # 6
print(math.gcd(12, 18, 30)) # 6
print(math.lcm(4, 6)) # 12
# Reduce a fraction by dividing both parts by their gcd
num, den = 12, 18
g = math.gcd(num, den)
print(f"{num // g}/{den // g}") # 2/3Exact integer square roots
math.isqrt(n) returns the floor of the square root of n as an int. It works on integers directly, so it stays exact for very large values. math.sqrt converts its argument to a float first, which can lose precision.
import math
print(math.isqrt(17)) # 4
print(math.isqrt(10**30 - 1)) # 999999999999999
print(int(math.sqrt(10**30 - 1))) # 1000000000000000, which is wrongThe last line is wrong because 10**30 - 1 rounds to the float 1e30 before the square root is taken. isqrt has no such step.
A common use is limiting a search. If n has a divisor larger than its square root, it must also have one smaller, so a primality test only needs to check up to isqrt(n):
import math
def is_prime(n):
if n < 2:
return False
for d in range(2, math.isqrt(n) + 1):
if n % d == 0:
return False
return True
print([n for n in range(20) if is_prime(n)]) # [2, 3, 5, 7, 11, 13, 17, 19]Common errors
| Mistake | What happens |
|---|---|
| `math.factorial(-1)` | Raises `ValueError`. Factorial is undefined for negative numbers. |
| `math.comb(5, -1)` | Raises `ValueError`. Both arguments must be non-negative. |
| `math.isqrt(-4)` | Raises `ValueError`. Use `cmath.sqrt` if you need complex results. |
| `math.comb(5, 2.0)` | Raises `TypeError`. These functions require integers, not floats. |
| `math.factorial(5000)` | Works, but produces a number with over 16,000 digits. Large inputs cost time and memory. |
Exercise
A club has 8 members. (a) How many ways can it choose a 3-person committee? (b) How many ways can it choose a president, vice president, and treasurer? (c) Write one line that computes the largest whole number whose square is at most 1000.
Show answer
(a) math.comb(8, 3) = 56, because order doesn't matter. (b) math.perm(8, 3) = 336, because the three roles make order matter. (c) math.isqrt(1000) = 31, since 31² = 961 and 32² = 1024.