문제

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/

도움이 되었습니까?

해결책

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);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top