Python recursive program to prime factorize a number

前端 未结 5 583
庸人自扰
庸人自扰 2021-01-22 14:07

I wrote the following program to prime factorize a number:

import math
def prime_factorize(x,li=[]):
    until = int(math.sqrt(x))+1
    for i in xrange(2,until)         


        
5条回答
  •  有刺的猬
    2021-01-22 14:31

    If you want to do it completely recursive, I'd recommend this code, it does return the correct answer and the way it works is pretty clear. If you want to make the program as efficient as possible I'd recommend you to stick to one of your previous methods.

    def primeFact (i, f):
        if i < f:
            return []
        if i % f == 0:
            return [f] + primeFact (i / f, 2)
        return primeFact (i, f + 1)
    

    This is a completely recursive way of solving your problem

    >>> primeFact (300, 2)
    [2, 2, 3, 5, 5]
    >>> primeFact (17, 2)
    [17]
    >>> primeFact (2310, 2)
    [2, 3, 5, 7, 11]
    

提交回复
热议问题