Collatz sequence of a number

4.6k views Asked by At

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

1

There are 1 answers

0
Kyle Lemons On

You aren't checking whether the number is overflowing your long. Try adding the following print in your loop:

...
      if (number*3+1 < number) {
        printf("overflow after %d iterations\n", length);
        break;
      }
      number = (number * 3) + 1;
...

Note that whether this overflows a long will depend on the system/target:

/tmp/c $ gcc -o collatz -m32 collatz.c
/tmp/c $ ./collatz 
overflow after 120 iterations
/tmp/c $ gcc -o collatz -m64 collatz.c
/tmp/c $ ./collatz 
<answer redacted>

You might also consider using a unsigned long long which should be large enough for this problem even in 32-bit.