Given two integer a and b, find whether their product (a x b) exceed the signed 64 bit integer or not. If it exceed print Yes else print No.
Examples:
Input : a = 100, b = 200
Output : No
Input : a = 10000000000, b = -10000000000
Output : Yes
Approach :
- If either of the number is 0, then it will never exceed the range.
- Else if the product of the two divided by one equals the other, then also it will be in range.
- In any other case overflow will occur.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
bool isOverflow(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 (isOverflow(a, b))
cout << "Yes";
else
cout << "No";
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class GfG{
static Boolean isOverflow( long a, long b)
{
if (a == 0 || b == 0)
return false;
long result = a * b;
if (a == result / b)
return false;
else
return true;
}
public static void main(String argc[])
{
long a = Long.parseLong("10000000000");
long b = Long.parseLong("-10000000000");
if (isOverflow(a, b))
System.out.print("Yes");
else
System.out.print("No");
}
}
|
Python3
def isOverflow(a, b):
if (a == 0 or b == 0) :
return False
result = a * b
if (result >= 9223372036854775807 or
result <= -9223372036854775808):
result=0
if (a == (result // b)):
print(result // b)
return False
else:
return True
if __name__ =="__main__":
a = 10000000000
b = -10000000000
if (isOverflow(a, b)):
print( "Yes")
else:
print( "No")
|
C#
using System;
public class GfG
{
static bool isOverflow( long a, long b)
{
if (a == 0 || b == 0)
return false;
long result = a * b;
if (a == result / b)
return false;
else
return true;
}
public static void Main()
{
long a = 10000000000;
long b = -10000000000 ;
if (isOverflow(a, b))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
|
PHP
<?php
function isOverflow($a, $b)
{
if ($a == 0 || $b == 0)
return false;
$result = $a * $b;
if ($a == (int)$result / $b)
return false;
else
return true;
}
$a = 10000000000;
$b = -10000000000;
if (isOverflow($a, $b))
echo "Yes";
else
echo "No";
?>
|
Javascript
<script>
function isOverflow(a, b)
{
if (a == 0 || b == 0)
return false;
var result = a*b;
if (result >= 9223372036854775807 ||
result <= -9223372036854775808)
result=0
if (a == parseInt(result / b))
return false;
else
return true;
}
var a = 10000000000, b = -10000000000;
if (isOverflow(a, b))
document.write( "Yes");
else
document.write( "No");
</script>
|
Time complexity: O(1)
Auxiliary space: O(1)
Last Updated :
22 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...