The answer is probably blindingly obvious but for the life of me I can't see it. I am trying to find out how many iterations it takes for a user-supplied positive integer to converge to 1 (i.e. recursive function is f(x)=x/2 if x even, 3x+1 if x odd). The answer is trivial if done brute force (i.e. through a series of if statements). I am however aiming for a recursive approach, and am stuck in an infinite loop:
#include <stdio.h>
int collatz(long number, int length)
{
while (number != 1)
{
length++;
printf("%ld\n", number);
if ((number % 2) == 0)
collatz(number/2,length);
else
collatz(3*number+1,length);
}
return length;
}
int main()
{
long number;
printf("Input a number\n");
scanf("%ld", &number);
int length=1;
printf("length is %d", collatz(number,length));
return 0;
}
The problem occurs when number=1. Instead of the loop terminating, it continues and so it oscillates between 1 and 2 indefinitely.