Check for integer overflow on multiplication in C++

C++Server Side ProgrammingProgramming

Suppose we want to find the result after multiplying two numbers A and B. We have to check whether the multiplied value will exceed the 64-bit integer or not. If we multiply 100, and 200, it will not exceed, if we multiply 10000000000 and -10000000000, it will overflow.

To check this, we have to follow some steps. These are like below −

Steps

  • If anyone of the numbers is 0, then it will not exceed

  • Otherwise, if the product of two divided by one equals to the other, then it will not exceed

  • For some other cases, it will exceed.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
bool isMulOverflow(long long A, long long B) {
   if (A == 0 || B == 0)
      return false;
   long long result = A * B;
   if (A == result / B)
      return false;
   else
      return true;
}
int main() {
   long long a = 10000000000 , b = -10000000000;
   if(isMulOverflow(a, b)){
      cout <<"It will overflow";
   }
   else{
      cout <<"It will not overflow";
   }
}

Output

It will overflow
raja
Published on 21-Oct-2019 08:23:35
Advertisements