Sub topic 2
Prime Factorization and the Factor Tree
This chapter assumes you can do integer arithmetic, read exponent notation such as 2^3, and know what it means for one integer to divide another.
Prime factorization and the factor tree
A prime is an integer greater than 1 whose only positive divisors are 1 and itself. A composite is an integer greater than 1 that is not prime. Every integer greater than 1 can be written as a product of primes in exactly one way, apart from the order of the factors. That product is its prime factorization.
A factor tree finds this product. Split the number into any two factors, then split each composite factor again until only primes remain.
The leaves give 2 x 2 x 2 x 3 x 3 x 5, which is 2^3 x 3^2 x 5. The split order changes the tree but not the final list of primes.
def prime_factors(n):
factors = {}
p = 2
while p * p <= n:
while n % p == 0:
factors[p] = factors.get(p, 0) + 1
n //= p
p += 1
if n > 1:
factors[n] = factors.get(n, 0) + 1
return factors
print(prime_factors(360)) # {2: 3, 3: 2, 5: 1}Counting the factors of an integer
Once you have the factorization, you can count the positive divisors without listing them. A divisor picks an exponent for each prime, from 0 up to that prime's exponent. If n = p^a x q^b x ..., the number of positive divisors is (a + 1)(b + 1) ...
| Prime | Exponent | Choices (exponent + 1) |
|---|---|---|
| 2 | 3 | 4 |
| 3 | 2 | 3 |
| 5 | 1 | 2 |
So 360 has 4 x 3 x 2 = 24 positive divisors.
Perfect squares and the odd number of factors
Divisors come in pairs: if d divides n, then n/d also divides n. The pairs match up except when d equals n/d, which means d is the square root of n. So a perfect square has one unpaired divisor, and its divisor count is odd. For 36, the pairs are (1, 36), (2, 18), (3, 12), (4, 9), and (6, 6), giving 9 divisors.
> The number of divisors is odd exactly when every prime exponent is even, which is the same as n being a perfect square.
Check this rule with the exponent formula. If every exponent is even, each factor (exponent + 1) is odd, and an odd product is odd.
GCD and LCM from prime factorizations
The greatest common divisor (GCD) of two integers takes the smallest exponent of each shared prime. The least common multiple (LCM) takes the largest exponent of each prime that appears in either number.
For 84 = 2^2 x 3 x 7 and 90 = 2 x 3^2 x 5, the GCD is 2^1 x 3^1 = 6 and the LCM is 2^2 x 3^2 x 5 x 7 = 1260. Their product, 7560, equals 84 x 90.
from math import gcd
a, b = 84, 90
g = gcd(a, b)
l = a * b // g
print(g, l) # 6 1260
print(g * l == a * b) # TrueExercise
How many positive divisors does 72 have, and what is GCD(72, 108)?
Show answer
72 = 2^3 x 3^2 has (3 + 1)(2 + 1) = 12 divisors. 108 = 2^2 x 3^3, so the GCD takes 2^2 x 3^2 = 36.