Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime error: signed integer overflow: 2 * 2147483647 cannot be represented in type 'int'

I am trying to run the following code:

 int across(vector<int> &nums, int l , int m, int h){
 
        
        int i = l, j = m +1;
        int count = 0;
        unsigned long long int n;
        unsigned long long int prev;
        
        while(i <= m && j <=h){
            n = 2* nums[j];
            prev = nums[i];
            if(prev > n){
                count += m - i +1;
                j++;
            }
            else{
                i++;
            }
        }
        
        return count;
    }

nums is a vector sorted from index l to m and from index m+1 to h. I have to count number of pairs(i, j) such that nums[i] > 2 * nums[j]

I am getting runtime error when one of the element is 2147483647.

I tried using long long int and unsigned long long int but still shows the same.

Please help me get rid of this.

like image 340
Dark Night Avatar asked May 02 '26 06:05

Dark Night


1 Answers

In C++, the type of the left-hand side of an assignment (=) does not affect the type of right-hand side.

       n = 2* nums[j];

Here the expression is 2* nums[j], and since both 2 and nums[j] are of type int, the result is still of type int. The type of n plays no role.

Cast at least one of the arguments to long long to get a long long result:

       n = 2LL* nums[j];

Or

       n = 2* (long long) nums[j];
like image 158
rustyx Avatar answered May 03 '26 19:05

rustyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!