Overflow in unsigned long int - C

Asked

Viewed 106 times

1

The unsigned long int type 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 variable long int. 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 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?

  • 1

    looking at the surface, I think where "float overflow = 3 * n + 1;" should be "float overflow = 3.0 * n + 1;" to avoid possible overflow in operations " 3 * n + 1", which are made in integer.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.