Python recursive program to prime factorize a number

前端 未结 5 587
庸人自扰
庸人自扰 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:27

    A more functional-style version.

    def prime_factorize( number ):
        def recurse( factors, x, n ):
            if x<2: return factors # 0,1 dont have prime factors
            if n > 1+x**0.5: # reached the upper limit
                factors.append( x ) # the only prime left is x itself
                return factors
            if x%n==0: # x is a factor
                factors.append( n )
                return recurse( factors, x/n, n )
            else:
                return recurse( factors, x, n+1 )
        return recurse( [], number, 2)
    
    for num, factors in ((n, prime_factorize( n )) for n in range(1,50000)):
        assert (num==reduce(lambda x,y:x*y, factors, 1)), (num, factors)
        #print num, ":", factors
    

提交回复
热议问题