Print all unique combination of factors of a given number

后端 未结 9 723
挽巷
挽巷 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:41

    I came up with this, seems easy to read and understand. Hope it helps!

    def getFactors(num):
    
        results = []
    
        if num == 1 or 0:
            return [num]
    
        for i in range(num/2, 1, -1):
    
            if (num % i == 0):
                divisor = num / i
    
                if(divisor <= i):
                    results.append([i, divisor])
    
                innerResults = getFactors(divisor)
    
                for innerResult in innerResults:
                    if innerResult[0] <= i:
                        results.append([i] + innerResult)
    
        return results
    

提交回复
热议问题