I am trying to write this recursive function:
void printFactors(int n)
For this function, I need to print prime factors in ascending order. e.g. for n = 24 the output would be 2 2 2 3. I cannot use loops and static variables for this function.
Here is my solution:
void printFactors(int n)
{
int div = 2;
if(n == 1)
{
div = 2;
return;
}
else if(n % div == 0)
{
cout << div << " ";
printFactors(n/div);
}
else
{
div++;
printFactors(n);
}
}
int main()
{
int n = 5;
cout << "Factors of 5: ";
printFactors(n);
cout << endl;
int n2 = 16;
cout << "Factors of 16: ";
printFactors(n2);
cout << endl;
int n3 = 24;
cout << "Factors of 24: ";
printFactors(n3);
cout << endl;
int n4 = 63;
cout << "Factors of 63: ";
printFactors(n4);
cout << endl;
return 0;
}
After testing this code, my program crashed. Is there something that needs to be fixed in the printFactors() function?