Reputation: 155
I am trying to create some code that when given a starting number attempts to find the length of the corresponding collatz chain.
I was hoping to do this recursively and this is what I have so far :
#include stdio.h
int collatz(int number, int count)
{
if(number == 1)
{
return count;
}
if(number%2==0)
{
number = number/2;
collatz(number, count+1);
}
else
{
number = number*3+1;
collatz(number,count+1);
}
return 0;
}
int main(void)
{
int stored=0;
int temp;
for(int i = 1;i<10;i++)
{
temp = collatz(i,1);
if(temp>stored)
{
stored = temp;
}
}
printf("%i\n",stored);
}
The problem is of course that the function eventually reaches its endpoint, but then gets returned as the length of the chain and this becomes the new number..
How can I structure this program so that when the count reaches its endpoint I can take this value as the output of the very first call?
Upvotes: 1
Views: 7922
Reputation: 385890
You need to return the result of the recursive call. Right now you're ignoring the value of the recursive call and returning 0. Each recursive call should look like this:
return collatz(number, count+1);
Upvotes: 2