Skip to content Skip to sidebar Skip to footer

Prime Factorization Of A Number

I'm trying to write a program to find all the prime factors of a given number, and tried the following: def factors(nr): i = 2 factors = [] while i

Solution 1:

The simplest change you can make to fix your problem is to change your while loop condition:

def factors(nr):
    i = 2
    factors = []
    while i <= nr:
        if (nr % i) == 0:
            factors.append(i)
            nr = nr / i
        else:
            i = i + 1
    return factors

print factors(8)
print factors(9)
print factors(10)

Output

[2, 2, 2]
[3, 3]
[2, 5]

Solution 2:

def ba(n):
    pfa=[]
    y=n
    for i in range(n):
        if (i!=0 and i!=1):
            while (y%i==0):
                pfa.append(i)
                y=y/i
    print(pfa)

Post a Comment for "Prime Factorization Of A Number"