Dark Night
Dark Night

Reputation: 53

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.

Upvotes: 3

Views: 5510

Answers (1)

rustyx
rustyx

Reputation: 85531

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];

Upvotes: 8

Related Questions