cloopsif-statementansi-ccollatz

Stuck in Loop Collatz Conjecture Attempt in C


There is a logic flaw within my code that I can't seem to pass 2^31 − 1 as an input. Here is a fragment of my code.

#include <stdio.h>
int main() {
long input = 0;
long temp = 0;
int count = 0;
printf("Enter a positive integer ( or 0 to quit): ");
scanf("%ld", &input);
if(input == 0)
{
    printf("Quit.");
}
else
{
    temp = input;
    while (temp != 1)
    {
        if(temp %2 ==0)
        {
            temp = temp/2;
            count++;


        } else
        {
            temp = 3*temp + 1;
            count++;
        }

    }
return 0;
}

I have tried changing the size of my input to long => long long and it still get stuck within this area after Debugging it. Please provide some feedback Thanks!


Solution

  • Assuming your system has a long of 64 bits, then changing it to work with unsigned long, including scanf(), seems to work fine:

    #include <stdio.h>
    #include <assert.h>
    
    int main() {
        unsigned long input;
        assert(sizeof(input) * 8 >= 64);
    
        while (1) {
            printf("Enter a positive integer (or 0 to quit): ");
            (void) scanf("%lu", &input);
    
            if (input == 0) {
                break;
            }
    
            unsigned int count = 0;
    
            while (input != 1) {
                if (input % 2 == 0) {
                    input /= 2;
                } else {
                    input = 3 * input + 1;
                }
                count++;
            }
    
            printf("%d\n", count);
        }
    
        printf("Quit.\n");
    
        return 0;
    }
    

    USAGE

    > ./a.out
    Enter a positive integer (or 0 to quit): 2147483647
    450
    Enter a positive integer (or 0 to quit): 0
    Quit.
    >
    

    Otherwise, find some other 64 bit type (long long?) to use. Python works as it has infinitely large integers.