Print all unique combination of factors of a given number

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

    Try this recursive approach that also takes in 2 more inputs namely a string to carry over the current value of i in for loop to perform subsequent reduction and also a temp int to know when not to print duplicate reversals i.e., 8*3 and 3*8.

    public static void printFactors(int number, String parentFactors, int parentVal) {
        int newVal = parentVal;
        for (int i = number - 1; i >= 2; i--) {
    
            if (number % i == 0) {
                if (newVal > i) {
                    newVal = i;
                }
                if (number / i <= parentVal && i <= parentVal
                        && number / i <= i) {
                    System.out.println(parentFactors + i + "*" + number / i);
                    newVal = number / i;
                }
    
                if (i <= parentVal) {
                    printFactors(number / i, parentFactors + i + "*", newVal);
                }
            }
    
        }
    
    }
    

    And call this method using printFactors(12,'',12)
    Let me know if you find flaws in this approach. Thanks!

提交回复
热议问题