Home > Back-end >  Why do I need to convert my two variables from int to long long int in the provided case?
Why do I need to convert my two variables from int to long long int in the provided case?

Time:08-11

I was solving a programming question (problem 633 on Leetcode).

The below code does not run, it gives this error:

runtime error: signed integer overflow: 829921 2146654224 cannot be represented in type 'int'

bool judgeSquareSum(int c)
{
    int h=sqrt(c),l=0;
    
    while(l<=h)
    {
        long long sum=l*l h*h;
        if(sum>c)
        {
            h--;
        }
        else
            if(sum<c)
                l  ;
            else
                return true;
    }

    return false;
}

Whereas the below code runs perfectly. The only difference is, variables l and h are of long long type as compared to int type in the above code.

To specify - l and h cannot have values greater than INT_MAX neither l*l and h*h can be greater than INT_MAX.

bool judgeSquareSum(int c) {
    long long l = 0, h = sqrt(c);
    while (h >= l) {
        long long xxxx = l * l   h * h;
        if (xxxx > c) {
            h--;
        } else if (xxxx < c) {
            l  ;
        } else {
            return true;
        }
    }
    return false;
}

CodePudding user response:

The error message is telling you precisely what the problem is:

signed integer overflow: 829921 2146654224 cannot be represented in type 'int'

You're trying to add the values 829921 and 2146654224 and the result (which should be 2147484145) does not fit in an int. This tells us that you're almost certainly running on a machine where INT_MAX is 231-1 or 2147483647

This would appear to be coming from the line

long long xxxx = l * l   h * h;

where l and h both have type int so the expression l * l h * h will be evaluated as type int. The fact that the value will be used to initialize a value of type long long is irrelevant -- in C (and C ) the type and precision of expression is determined solely from the types of the operands and not from how the result will be used.

CodePudding user response:

long long has a size of at least 64 bits. int has at least a size of 16 bits. Therefore not all numbers that you can represent in long long can also be represented as int without value loss, hence the need for the larger type. See more here: https://en.cppreference.com/w/cpp/language/types

  • Related