Lesson 3 of 15
Divisors
Divisors of a Number
A divisor (or factor) of is an integer such that (i.e., ). Finding all divisors of a number is a foundational task in number theory.
Efficient Divisor Finding
A naive approach checks all integers from to , which is . We can do better: divisors come in pairs where , so we only need to check up to :
def divisors(n):
divs = []
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divs.append(i)
if i != n // i: # avoid duplicating perfect-square root
divs.append(n // i)
return sorted(divs)
print(divisors(12)) # [1, 2, 3, 4, 6, 12]
This runs in time.
Number of Divisors
The divisor function (also written or ) counts how many divisors has. If , then:
For example, so .
def count_divisors(n):
return len(divisors(n))
print(count_divisors(12)) # 6
Highly Composite Numbers
Numbers with unusually many divisors are called highly composite numbers: 1, 2, 4, 6, 12, 24, 36, 48, 60, …
Your Task
Implement divisors(n) returning a sorted list of all divisors of , and count_divisors(n) returning the count.
Python runtime loading...
Loading...
Click "Run" to execute your code.