calculate prime factors of 216 in python

To calculate the prime factors of 216 in Python, we can use a loop to divide the number by all possible prime factors from 2 to the square root of the number. If a prime factor is found, we divide the number by that factor, and repeat the process until the remainder is not divisible by any factor. The code can be written as follows:

main.py
import math

def prime_factors(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

print(prime_factors(216))
325 chars
17 lines

Output:

main.py
[2, 2, 2, 3, 3, 3]
19 chars
2 lines

This means that the prime factors of 216 are 2, 2, 2, 3, 3, and 3.

gistlibby LogSnag