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
I have a solution without recursion or sorting or stacks in C/C++.
#include
#include
// For each n, for each i = n-1 to 2, try prod = prod*i, if prod < N.
int
g(int N, int n, int k)
{
int i = k;
int prod = n;
std::vector myvec;
myvec.push_back(n);
while (i > 1) {
if (prod * i == N) {
prod = prod*i;
myvec.push_back(i);
for (auto it = myvec.begin();
it != myvec.end(); it++) {
std::cout << *it << ",";
}
std::cout << std::endl;
return i;
} else if (prod * i < N) {
prod = prod*i;
myvec.push_back(i);
} else { i--;}
}
return k;
}
void
f(int N)
{
for (int i = 2; i <= N/2; i++) {
int x = g(N, i, i-1);
// Extract all possible factors from this point
while (x > 0) {
x = g(N, i, x-1);
}
}
}
int
main()
{
f(24);
return 0;
}
And output is like this:
$ ./a.out
3,2,2,2,
4,3,2,
6,4,
6,2,2,
8,3,
12,2,