Search code examples
pythondiscrete-mathematicsprime-factoring

python program to expand a number in to prime factors


there is some glitch in my code

pls make it better


def factors (num):
    #num =  int( eval(input ("enter a number : ") ))

    to = (num//2)+2
    dict = []

    for a in range(2,to):
        for b in range (2,a+1):
            if num % b == 0:
                dict.append(b)
                num = num // b

    print (dict)

factors(2*2*2*2*2*2*2*2*2*2*2*2*2)

desired outcome is

[2,2,2,2,2,2,2,2,2,2,2]

but I an getting something like this

[2, 2, 2, 4, 2, 4, 2, 4, 2, 2]

Solution

  • def factors(num):
        d = []
        while num > 1:
            for a in range(2, num+1):
                if num % a == 0:
                    d.append(a)
                    num = num // a
                    break
        print(d)
    
    
    factors(2 ** 14) # [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]