Prime factorization - list

前端 未结 17 836
说谎
说谎 2020-11-27 05:06

I am trying to implement a function primeFac() that takes as input a positive integer n and returns a list containing all the numbers in the prime

17条回答
  •  独厮守ぢ
    2020-11-27 05:25

    A simple trial division:

    def primes(n):
        primfac = []
        d = 2
        while d*d <= n:
            while (n % d) == 0:
                primfac.append(d)  # supposing you want multiple factors repeated
                n //= d
            d += 1
        if n > 1:
           primfac.append(n)
        return primfac
    

    with O(sqrt(n)) complexity (worst case). You can easily improve it by special-casing 2 and looping only over odd d (or special-casing more small primes and looping over fewer possible divisors).

提交回复
热议问题