how to factor a prime number in python in python

Here's a Python function to factor a prime number using trial division:

main.py
import math

def factorize(n):
    """Return a list of the prime factors of n."""
    factors = []
    while n % 2 == 0:
        factors.append(2)
        n //= 2
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            factors.append(i)
            n //= i
    if n > 2:
        factors.append(n)
    return factors
347 chars
16 lines

You can call this function like so: factorize(131) and it will return [131]. If you call factorize(156) it will return [2, 2, 3, 13], which are the prime factors of 156.

gistlibby LogSnag