Python factorization

前端 未结 5 1393
清歌不尽
清歌不尽 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 19:33

    Yes. When you've got an algorithm that needs n nested for loops, you can usually turn it into a recursive function:

    def print_factors(d, product=1):
        if len(d) == 0:      # Base case: we've dealt with all prime factors, so
            print product    # Just print the product
            return
        d2 = dict(d)         # Copy the dict because we don't want to modify it
        k,v = d2.popitem()   # Pick any k**v pair from it
        for i in range(v+1): # For all possible powers i of k from 0 to v (inclusive)
                             # Multiply the product by k**i and recurse.
            print_factors(d2, product*k**i)
    
    d = {2:3, 3:2, 5:1}
    print_factors(d)
    

提交回复
热议问题