Write a program that takes an integer and prints out all ways to multiply smaller integers that equal the original number, without repeating sets of factors. In other words, if your output contains 4 * 3, you should not print out 3 * 4 again as that would be a repeating set. Note that this is not asking for prime factorization only. Also, you can assume that the input integers are reasonable in size; correctness is more important than efficiency. PrintFactors(12) 12 * 1 6 * 2 4 * 3 3 * 2 * 2
public void printFactors(int number) {
printFactors("", number, number);
}
public void printFactors(String expression, int dividend, int previous) {
if(expression == "")
System.out.println(previous + " * 1");
for (int factor = dividend - 1; factor >= 2; --factor) {
if (dividend % factor == 0 && factor <= previous) {
int next = dividend / factor;
if (next <= factor)
if (next <= previous)
System.out.println(expression + factor + " * " + next);
printFactors(expression + factor + " * ", next, factor);
}
}
}
I think it is
If the given number is N and the number of prime factors of N = d, then the time complexity is O(N^d). It is because the recursion depth will go up to the number of prime factors. But it is not tight bound. Any suggestions?
nextnext
isn't defined. – Crepe* 1
-product" can be placed in the single parameter method where it doesn't need to be controlled. Turning expression toStringBuilder
impedes readability and doesn't really help: "each" String gets printed. Iffactor <= previous
,next <= factor
impliesnext <= previous
. Out of principle, I'd initialisefactor = Math.min(dividend/2, previous)
.) – Rice