
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check for Integer Overflow on Multiplication in C++
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
#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
Advertisements