71. Prime factors
Every whole number above 1 is a product of primes in exactly one way: 360 = 2 2 2 3 3 * 5. A prime is a number above 1 that only 1 and itself divide: 2, 3, 5, 7, 11, and so on.
Write a function prime_factors(n) that takes a whole number n and returns the list of primes that multiply to
make it, from smallest to largest, each repeated as often as it divides n.
- A prime gives a list of just itself: 97 gives
[97]. - 1 is a product of no primes, so it gives
[]. ncan be as large as ten thousand million, so trying every number up tontakes far too long. A number that isn't prime always has a factor no bigger than its square root.
Example 1
n = 12[2, 2, 3]Example 2
n = 97[97]Example 3
n = 1[]Constraints
nis a whole number from 1 to 10,000,000,000 (10^10).
Submit also runs 10 more tests you can't see.
Practises While Loops (lesson 14).
- Try divisors
dfrom 2 upward. Whilen % d == 0, adddto the list and divide it out withn //= d: 12 gives 2, then 6 gives 2, then 3 isn't divisible by 2. - Because each factor is divided out completely, a non-prime like 4 never divides what is left. You only ever collect primes.
- Stop once
d * d > n. Whatever is left ofn, if it is more than 1, is a prime too big to have been reached: add it (14 leaves 7 after the 2).
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def prime_factors(n):
"""Break n into its prime factors.
n: int, 1 or more
Returns: list of int, the primes whose product is n,
smallest first, with repeats
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.