Python Program to Find Prime Factors Of A Given Number

Prime factors of a number are those prime numbers which on multiplying together we get original number.

Prime factor examples:
Prime factors of 18 are = [2, 3, 3] so that 2 * 3 * 3 = 18 where 2 & 3 are prime numbers.

Prime factors of 4620 are: [2, 2, 3, 5, 7, 11]

This Python program calculates list of all prime factors of a given number by user.

Python Source Code: Prime Factors


# Function definition to get all prime factors
def get_prime_factors(n):
    i = 2
    prime_factors = []
    while i*i <= n:
        if n%i == 0:
            prime_factors.append(i)
            n //= i
        else:
            i += 1
    
    if n>1:
        prime_factors.append(n)
    
    return prime_factors

# Read number from user
number = int(input('Enter number: '))

# Function call
prime_factors = get_prime_factors(number)

# Displaying prime factors
print("Prime factors are: ", prime_factors)

Output

Run 1:
---------------------
Enter number: 4620
Prime factors are:  [2, 2, 3, 5, 7, 11]

Run 2:
---------------------
Enter number: 12321
Prime factors are:  [3, 3, 37, 37]