I need to write a recursive function to print the prime factoring elements of an integer, ascending.
void printPrimeFactors(int num)
{
int div;
if (isPrime(num) == true)
cout << num << " ";
else
{
for (div = 2; div < num; div++)
{
if (isPrime(div) == true && num%div == 0)
printPrimeFactors(num/div);
}
}
What am I doing wrong? My output, for 20 is:
5 2 5 2 2
My smallest input is a prime number and a smaller input for the recursive function is num div (smallest prime divider of num).
I believe the following will work:
As requested, it is recursive, even though recursion isn’t necessary and can be trivially converted into iteration.
The reason your original version doesn’t quite work is twofold: