Home > Net >  Max Pairwise Product problem integer overflow
Max Pairwise Product problem integer overflow

Time:06-14

#include<algorithm>
#include <iostream>
#include<vector>
using namespace std;

long long MaxPairwise(const std::vector<int>& nums){
    long long product = 0;
    int n;
    n=nums.size();
    int index1=-1;
    for(int i=0;i<n;i  ){
        if(index1==-1  || nums[index1]<nums[i]){
            index1=i;
        }
       
    }
    int index2=-1;
    for(int j=0;j<n;j  ){
        if(index1!=j && nums[index2]<nums[j]){
            index2=j;
        }
        
    }
    product=nums[index2]*nums[index1];
    return ((long long)(product));
}

int main()
{
    int n;
    cin>>n;
     std::vector<int> nums(n);
    for(int i=0;i<n;i  ){
        std::cin>>nums[i];
    }
    long long result;
    result= MaxPairwise(nums);
    cout<<result<<'\n';
    
    return 0;
}

It causes an integer overflow for inputs 900000 100000, even though I have assigned a long long type to the variables. How do I fix this? I have tried changing the types but cannot figure it out and need help.

CodePudding user response:

product = 1LL * nums[index2] * nums[index1]; forces conversion of the coefficients on the right hand side to the long long type.

Otherwise the type of the product is an int, with possible overflow effects.

Using std::vector<long long> is another option.

Note that nums.size(); is a std::vector<int>::size_type type. That's certainly unsigned, and likely to be a std::size_t. In other words there's another possibility of overflow in using an int there.

  • Related