Prime factorization - list

前端 未结 17 895
说谎
说谎 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:10

    I've tweaked @user448810's answer to use iterators from itertools (and python3.4, but it should be back-portable). The solution is about 15% faster.

    import itertools
    
    def factors(n):
        f = 2
        increments = itertools.chain([1,2,2], itertools.cycle([4,2,4,2,4,6,2,6]))
        for incr in increments:
            if f*f > n:
                break
            while n % f == 0:
                yield f
                n //= f
            f += incr
        if n > 1:
            yield n
    

    Note that this returns an iterable, not a list. Wrap it in list() if that's what you want.

提交回复
热议问题