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?

Your problem is that `div` is re-initialized each time the function runs, leading to a stack overflow error. Making `div` an optional parameter with a default value of 2 and passing the new value at each recursion, is one way around this:

``void printFactors(int n, …``

## All 3 Replies

Your problem is that `div` is re-initialized each time the function runs, leading to a stack overflow error. Making `div` an optional parameter with a default value of 2 and passing the new value at each recursion, is one way around this:

``````void printFactors(int n, int div = 2)
{
if (n == 1)
{
div = 2;
return;
}
else if (n % div == 0)
{
cout << div << " ";
printFactors(n / div, div);
}
else
{
div++;
printFactors(n, div);
}
}
``````

On a side note the code is much easier to read when it is properly indented.

Unfortunately, the only parameter I can use for this function is n. So, is there another way to fix the printFactors() function without having to make div an optional parameter?

You can also make `div` static. This means that the value will be persistent and not get re-declared:

``````void printFactors(int n)
{
static int div = 2;
if (n == 1)
{
div = 2;
return;
}
else if (n % div == 0)
{
cout << div << " ";
printFactors(n / div);
}
else
{
div++;
printFactors(n);
}
}
``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.