Search code examples
pythonrecursionprime-factoring

python recursive solution for prime factorization


I'm new to python and am really struggling trying to understand recursion. I wrote a function that takes one integer and returns a list of all numbers in the prime factorization of the number.

I wrote this iteratively:

def primeFac(n):
    lst=[]
    c=2
    while c<=n:
        if n%c==0:
            n//=c
            lst.append(c)
        else:
            c+=1
    return lst

Which returns:

>>> primeFac(5)
[5]
>>> primeFac(72)
[2, 2, 2, 3, 3]

How can I do this recursively? It seems unnecessary, but I do need to learn to do this for my final exam.

This is what I wrote so far:

def primeFac(n):
    lst = []
    c = 2
    if n<=c:
        lst.append(n)
    else:
        while n%c!=0:
            c+=1
        if n==c:
            lst.append(n)
        else:
            lst.append(c)
            lst.append(primeFac(n//c))
        return lst

and I am getting:

>>> primeFac(5)
[5]
>>> primeFac(72)
[2, [2, [2, [3, [3]]]]]

Solution

  • your code is fine except for this :

        lst.append(primeFac(n//c))
    return lst
    

    you append the return, and return a list, so you will append a list to your list, on the "normal" iteration you used :

     lst.append(c)
    

    so you was appending just the value.

    you can do like this to concatenate the lists:

    lst = lst + primeFac(n//c))