50 XP

71. Prime factors

Intermediate math loops

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 [].
  • n can be as large as ten thousand million, so trying every number up to n takes far too long. A number that isn't prime always has a factor no bigger than its square root.

Example 1

Inputn = 12
Output[2, 2, 3]
Explanation12 = 2 * 2 * 3.

Example 2

Inputn = 97
Output[97]
Explanation97 is a prime itself.

Example 3

Inputn = 1
Output[]
Explanation1 has no prime factors.

Constraints

  • n is 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).

Code
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