I'm trying to find the Collatz sequence of a number. The following code runs into infinite loop for number 113383.
int collatz(long number) {
int length = 1; //length of the sequence
while (number != 1) {
printf("%ld-", number);
if ((number % 2) == 0)
number /= 2;
else
number = (number * 3) + 1;
length++;
}
return length;
}
int main() {
printf("%d", collatz(113383));
return 0;
}
EDIT: The Collatz Conjecture Says the next number in sequence is n/2 if number is even 3n+1 if the number is odd terminate if number is 1
You aren't checking whether the number is overflowing your
long
. Try adding the following print in your loop:Note that whether this overflows a
long
will depend on the system/target:You might also consider using a
unsigned long long
which should be large enough for this problem even in 32-bit.