Overflow in unsigned long int - C

1

The unsigned long int stores a maximum value of 4294967295 (2 ^ 32 - 1) while the float value stores a maximum of 10 ^ 38.

I'm doing an overflow test on an unsigned long int variable. Look at the code below, please.

The function below is a recursive function that calculates the number of steps that a given number l eva to converge to 1 according to the Collatz conjecture. Basically I want to test it is

#define max 4294967295

unsigned long int collatz(unsigned long int n, unsigned long int passos, unsigned long int *maiorN) {
    float overflow = 3 * n + 1;
    if (overflow > max)
        return -1;

    if (n == 1)
        return passos;
    else if (n % 2 == 0)
        return collatz(n / 2, passos + 1, maiorN);
    else { 
        if ((3 * n + 1) > *maiorN)
            *maiorN = 3 * n + 1;
        return collatz(3 * n + 1, passos + 1, maiorN);
    }    
}

Apparently this code is correct, at least from my point of view, but it seems to overflow earlier than expected.

Could someone take a look, please?

    
asked by anonymous 24.08.2018 / 18:57

0 answers