Print all unique combination of factors of a given number

后端 未结 9 988
挽巷
挽巷 2021-02-08 05:46

What is the most efficient algorithm to print all unique combinations of factors of a positive integer. For example if the given number is 24 then the output should be

9条回答
  •  粉色の甜心
    2021-02-08 06:18

    Here is my solution based on @rici's ideas.

    def factors(number, max_factor=sys.maxint):
        result = []
    
        factor = min(number / 2, max_factor)
        while factor >= 2:
            if number % factor == 0:
                divisor = number / factor
    
                if divisor <= factor and divisor <= max_factor:
                    result.append([factor, divisor])
    
                result.extend([factor] + item for item in factors(divisor, factor))
    
            factor -= 1
    
        return result
    
    print factors(12) # -> [[6, 2], [4, 3], [3, 2, 2]]
    print factors(24) # -> [[12, 2], [8, 3], [6, 4], [6, 2, 2], [4, 3, 2], [3, 2, 2, 2]]
    print factors(157) # -> []
    

提交回复
热议问题