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
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!