Rahul Kumawat
Rahul Kumawat

Reputation: 61

if i am taking A = 10^9 and B=10^9 than following code is giving negative output. why? It is giving me correct output for small integers

A and B are integers ranging from 1 to 10^9 , pairs is a variable that contain value of the expression ((A/2)(B/2)+((A-(A/2))(B-(B/2))))

#include<iostream>
    using namespace std;
    int main()
    {
        int T;
        cin>>T;
        while(T--)
        {
            long int A,B;
            cin>>A>>B;
            //cout<<A<<"    "<<B<<endl;
            long long int pairs = ((A/2)*(B/2)+((A-(A/2))*(B-(B/2))));
            cout<<pairs<<"\n";
        }
        return 0;
    }

Upvotes: 0

Views: 50

Answers (1)

CS Pei
CS Pei

Reputation: 11047

In many implementations, a long int in C++ is just a 32 bit number, the max is 2,147,483,647 . So if A is 10^9 and b is also 10^9, their product is beyond the max value of a 32 bit number (in fact A and B can be much smaller than 10^9 such that their product is beyond 2.15 billion). Therefore the product overflowed. As suggested in the comment,

you can change the definition of A and B to long long int

#include<iostream>
using namespace std;
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        long long int A,B; // here
        cin>>A>>B;
        //cout<<A<<"    "<<B<<endl;
        long long int pairs = ((A/2)*(B/2)+((A-(A/2))*(B-(B/2))));
        cout<<pairs<<"\n";
    }
    return 0;
}

Upvotes: 1

Related Questions