c++ - Keeping track of count in my recursive function(Collatz) -
i'm having trouble trying figure out how keep track of amount of times recursive function calls while performaing collatz function. have 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 keep track of number of times function calls itself? cannot seem life of me come solution. thanks!
reference collatz function: http://www.xamuel.com/collatz-recursion/
you trying compute length of collatz chain, aren't you. realise return 1
? should modify code return count instead. means adding current iteration 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); } }
Comments
Post a Comment