0

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?

2
Contributors
3
Replies
20
Views
2 Years
Discussion Span
Last Post by tinstaafl
0

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.

Edited by tinstaafl

0

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?

0

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);
    }
}

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.