Python recursive program to prime factorize a number

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

    @Anthony's correctly answered your original question about print. However, in the spirit of the several tips that were also offered, here's a simple refactorization using tail recursion removal:

    def prime_factorize(x):
      li = []
      while x >= 2:
        until = int(math.sqrt(x))+1
        for i in xrange(2,until):
          if not x%i:
            li.append(i)
            break
        else:
          li.append(x)
          return li
        x //= i
    

    This doesn't address the crucial performance issues (big-O behavior is the same as for your original solution) -- but since Python itself doesn't do tail-recursion optimization, it's important to learn to do it manually.

    "Change the [non-base-case] recursive steps 'return thisfun(newargs)' into args=newargs; continue and put the whole body into a while True: loop" is the basic idea of tail-recursion optimization. Here I've also made li a non-arg (no reason for it to be an arg), put a condition on the while, and avoided the continue since the recursive step was at the end of the body anyway.

    This formulation would be a good basis from which to apply further optimizing refactorings (sqrt avoidance, memoization, ...) to reach towards better performance.

提交回复
热议问题