Python factorization

前端 未结 5 1385
清歌不尽
清歌不尽 2020-12-16 19:03

I\'d just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.
For example if we have {2:3

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 19:18

    I have blogged about this, and the fastest pure python (without itertools) comes from a post by Tim Peters to the python list, and uses nested recursive generators:

    def divisors(factors) :
        """
        Generates all divisors, unordered, from the prime factorization.
        """
        ps = sorted(set(factors))
        omega = len(ps)
    
        def rec_gen(n = 0) :
            if n == omega :
                yield 1
            else :
                pows = [1]
                for j in xrange(factors.count(ps[n])) :
                    pows += [pows[-1] * ps[n]]
                for q in rec_gen(n + 1) :
                    for p in pows :
                        yield p * q
    
        for p in rec_gen() :
            yield p
    

    Note that the way it is written, it takes a list of prime factors, not a dictionary, i.e. [2, 2, 2, 3, 3, 5] instead of {2 : 3, 3 : 2, 5 : 1}.

提交回复
热议问题