Syntactic Fructose - 4 months ago 30

C++ Question

I'm having trouble trying to figure out how to keep track of the amount of times my recursive function calls itself while performaing collatz function. I have the function definition:

`template<class myType>`

myType recursionSet<myType>::collatz(myType n)

{

if(n == 1)

return 1;

else {

if(n%2 == 1)

return collatz(3*n+1);

else

return collatz(n/2);

}

}

how can i keep track of the number of times this function calls itself? I cannot seem for the life of me to come up with a solution. Thanks!

reference to collatz function: http://www.xamuel.com/collatz-recursion/

Answer

You are trying to compute the length of the Collatz chain, aren't you. Do you realise that currently you always return `1`

? You should modify your code to return the count instead. That means adding the current iteration to the recursive call:

```
template<class myType>
myType recursionSet<myType>::collatz(myType n)
{
if(n == 1)
return 1;
else {
if(n%2 == 1)
return 1 + collatz(3*n+1);
else
return 1 + collatz(n/2);
}
}
```