Can someone help correct my algorithm? I’ve tested it on a few numbers, and it doesn’t output the complete factorization. For numbers with a large number of factors, it just completely fails.
int num = 20;
for(int i = 2; i <= num; i++)
{
if(num%i == 0)
{
cout << i << endl;
cout << num << endl;
num = num/i;
}
}
EDIT: The two answers provided did not work, still not getting full results.
EDIT2: Divisors VS Factors
Judging from you comment to @
Luchian Grigore, you’re confusing divisors with (prime) factorization. Divisors of a number are all numbers for whichnum % i == 0is true. Factorization means getting a representation ofnumby a product of smaller numbers. If you want uniqueness of factorization, you usually use prime factorization.To get all the divisors your code should be
to get the (prime) factorization, it’s