First step is to find all the prime factors, with their multiplicity. Then you can generate the factors easily.
Finding the prime factors is quite fast on average for numbers up to about 100000000, if you do it sensibly. If you find a factor, you can divide it out of n
, which reduces the time enormously in the general case. Also you only need to check odd factors up to sqrt(n), apart from 2:
// I assume n is non-zero
while (!(n & 1)) {
cout << "2" << endl;
n /= 2;
}
for (unsigned int factor = 3; factor * factor <= n; factor += 2) {
while (n % factor == 0) {
cout << factor << endl;
n /= factor;
}
if (n != 1)
cout << n << endl;
}