Sub topic 5
Integer math: factorial, comb, perm, gcd, and isqrt
This chapter assumes you can run Python scripts, write simple functions, and know the difference between int and float. You should also have read the earlier chapters on importing from the standard library and on floating-point behavior in math.
The functions here work on integers and return exact integer results. They never go through floating-point arithmetic, so they avoid the rounding errors covered in the previous chapter. They are the right tools for counting problems, divisibility, and exact square roots.
Overview of the integer helpers
| Function | Returns | Example | Result |
|---|---|---|---|
| `math.factorial(n)` | n × (n−1) × … × 1 | `math.factorial(5)` | `120` |
| `math.comb(n, k)` | Ways to choose k items from n, order ignored | `math.comb(5, 2)` | `10` |
| `math.perm(n, k)` | Ways to arrange k items taken from n, order matters | `math.perm(5, 2)` | `20` |
| `math.gcd(a, b, ...)` | Greatest common divisor | `math.gcd(12, 18)` | `6` |
| `math.lcm(a, b, ...)` | Least common multiple | `math.lcm(4, 6)` | `12` |
| `math.isqrt(n)` | Floor of the square root, as an `int` | `math.isqrt(17)` | `4` |
comb and perm need Python 3.8 or later. Calling gcd or lcm with more than two arguments, and lcm itself, needs 3.9 or later.
factorial
The factorial of n is the product of all whole numbers from 1 to n. It counts how many ways you can order n distinct items.
import math
print(math.factorial(5)) # 120
print(math.factorial(1)) # 1
print(math.factorial(0)) # 1
print(math.factorial(20)) # 2432902008176640000factorial(0) is 1 by definition: there is exactly one way to arrange nothing. Factorials grow very fast, but Python integers have no fixed size, so the result is always exact. factorial(100) has 158 digits and Python computes it without overflow.
The function accepts only non-negative integers:
import math
for bad in (-1, 5.0, 2.5):
try:
math.factorial(bad)
except (ValueError, TypeError) as exc:
print(type(exc).__name__, "for", bad)A negative number raises ValueError. In Python 3.10 and later, any float raises TypeError, even a whole-valued one like 5.0. Older versions accepted 5.0 with a deprecation warning. Convert with int() if you know the value is whole.
comb and perm
Both functions answer "how many ways can I pick k items from n?" The difference is whether order counts.
perm(n, k)counts ordered selections. Picking Ana then Ben is different from Ben then Ana.comb(n, k)counts unordered selections. A committee of Ana and Ben is the same as a committee of Ben and Ana.
import math
print(math.perm(8, 3)) # 336: president, vice president, secretary
print(math.comb(8, 3)) # 56: a 3-person committee, no roles
print(math.perm(5)) # 120: with k omitted, perm(n) equals factorial(n)
print(math.comb(49, 6)) # 13983816: possible 6-number lottery ticketsThe two are related by comb(n, k) == perm(n, k) // factorial(k). Each unordered group of k items can be arranged in k! ways, so dividing removes the ordering. For 8 and 3, that is 336 // 6 = 56.
Why not write it with factorial yourself?
You can compute combinations from the textbook formula, and the result is the same:
import math
n, k = 5, 2
manual = math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
print(manual == math.comb(n, k)) # TrueThe built-in is better for two reasons. It is written to avoid building the full n! when only a small part of it is needed. It also handles the edge cases for you. Computing comb(1000, 500) this way takes noticeably more work than calling math.comb, because the manual version multiplies out three huge factorials first.
Edge cases
import math
print(math.comb(3, 5)) # 0: you cannot choose 5 items from 3
print(math.perm(3, 5)) # 0
print(math.comb(5, 0)) # 1: exactly one way to choose nothing
print(math.comb(5, 5)) # 1
try:
math.comb(-1, 2)
except ValueError as exc:
print("ValueError:", exc)When k is larger than n, both functions return 0 instead of raising an error. That is mathematically correct, but it can hide a bug if you swapped the arguments. Negative arguments raise ValueError, and non-integer arguments raise TypeError.
gcd and lcm
The greatest common divisor (GCD) of two integers is the largest integer that divides both without a remainder. The least common multiple (LCM) is the smallest positive integer that both divide into evenly.
import math
print(math.gcd(12, 18)) # 6
print(math.gcd(12, 18, 24)) # 6: any number of arguments (3.9+)
print(math.gcd(-12, 18)) # 6: the result is never negative
print(math.gcd(0, 5)) # 5
print(math.gcd(0, 0)) # 0
print(math.lcm(4, 6)) # 12
print(math.lcm(4, 0)) # 0The result is always non-negative, and gcd(0, 0) is 0 by convention. Zero is divisible by everything, so gcd(0, n) is abs(n). For lcm, any zero argument gives 0.
The two are linked: for positive integers, gcd(a, b) * lcm(a, b) == a * b.
Worked example: reducing a fraction
Dividing both parts of a fraction by their GCD puts it in lowest terms. Use floor division // so the results stay integers.
import math
def reduce_fraction(numerator, denominator):
if denominator == 0:
raise ValueError("denominator must not be zero")
divisor = math.gcd(numerator, denominator)
num, den = numerator // divisor, denominator // divisor
if den < 0: # keep the sign on the numerator
num, den = -num, -den
return num, den
print(reduce_fraction(12, 18)) # (2, 3)
print(reduce_fraction(6, -8)) # (-3, 4)
print(reduce_fraction(0, 5)) # (0, 1)If you used / instead of //, you would get floats like 2.0 and lose the exactness that made gcd useful. For real fraction work, the standard fractions.Fraction class does this reduction for you.
isqrt
math.sqrt returns a float. math.isqrt(n) returns the floor of the square root as an exact int: the largest integer r such that r * r <= n.
import math
print(math.isqrt(16)) # 4
print(math.isqrt(17)) # 4
print(math.isqrt(24)) # 4
print(math.isqrt(25)) # 5
print(math.sqrt(16)) # 4.0For small numbers the two agree, apart from the type. For large numbers, the float version is wrong, because a float holds only about 15 to 17 significant digits:
import math
n = 10**17 + 1
square = n * n
print(math.isqrt(square) == n) # True
print(int(math.sqrt(square)) == n) # FalseConverting square to a float discards the low digits before the square root is taken, so math.sqrt cannot return 10**17 + 1. isqrt works on the integer directly and stays exact at any size.
Checking for perfect squares
A number is a perfect square if squaring its integer square root gives the number back:
import math
def is_perfect_square(n):
if n < 0:
return False
root = math.isqrt(n)
return root * root == n
print([n for n in range(30) if is_perfect_square(n)])
# [0, 1, 4, 9, 16, 25]
print(is_perfect_square(10**30)) # True
print(is_perfect_square(10**30 + 1)) # Falseisqrt raises ValueError for negative input, so the function above guards against that case first. It also raises TypeError for floats, so convert with int() if needed.
Common mistakes
- Passing a float to
factorial,comb,perm, orisqrt. These needintvalues. In Python 3.10 and later they raiseTypeError. - Swapping
nandk. The result is0, not an error. - Using
permwhen order does not matter, orcombwhen it does. Ask whether swapping two chosen items gives a different outcome. - Dividing with
/aftergcd. Use//to stay in integers. - Using
int(math.sqrt(n))as an integer square root. It is fine for small values but wrong for large ones.
Exercises
Exercise
A club has 8 members. How many different 3-person committees can it form, and how many different ways can it fill the roles of president, vice president, and secretary? Which two function calls give the answers?
Show answer
math.comb(8, 3) gives 56 committees, because the order of members in a committee does not matter. math.perm(8, 3) gives 336 role assignments, because each role is different and order matters. As a check, 336 // math.factorial(3) equals 56.
Exercise
What do math.isqrt(99), math.gcd(84, 36), and math.lcm(84, 36) return? Is 99 a perfect square?
Show answer
math.isqrt(99) returns 9, since 9 9 = 81 is at most 99 and 10 10 = 100 is more. math.gcd(84, 36) returns 12. math.lcm(84, 36) returns 252, which matches 84 36 // 12. Because 9 9 = 81 is not 99, 99 is not a perfect square.