Given two large numbers ‘a’ and ‘b’ such that(10^20<=a, b<=10^300). Find the LCM of two large numbers given. Examples:
Input: a = 234516789234023485693020129
b = 176892058718950472893785940
Output: 41484157651764614525905399263631111992263435437186260
Input: a = 36594652830916364940473625749407
b = 448507083624364748494746353648484939
Output: 443593541011902763984944550799004089258248037004507648321189937329
Solution: In the given problem, we can see that the number are very large which is outside the limit of all available primitive data types, so we have to use the concept of BigInteger Class in Java. So we convert the given strings into biginteger and then we use java.math.BigInteger.gcd(BigInteger val) method to compute gcd of large numbers and then we calculate lcm using following formula: LCM * HCF = x * y, where x and y are two numbers Below is implementation of the above idea.
Java
import java.math.*;
import java.lang.*;
import java.util.*;
public class GFG {
public static BigInteger lcm(String a, String b)
{
BigInteger s = new BigInteger(a);
BigInteger s1 = new BigInteger(b);
BigInteger mul = s.multiply(s1);
BigInteger gcd = s.gcd(s1);
BigInteger lcm = mul.divide(gcd);
return lcm;
}
public static void main(String[] args)
{
String a = "36594652830916364940473625749407" ;
String b = "448507083624364748494746353648484939" ;
System.out.print(lcm(a, b));
}
}
|
Python3
import math
def lcm (a, b):
s = int (a)
s1 = int (b)
mul = s * s1
gcd = math.gcd(s, s1)
lcm = mul / / gcd
return lcm
if __name__ = = '__main__' :
a = "36594652830916364940473625749407"
b = "448507083624364748494746353648484939"
print (lcm(a, b))
|
Javascript
function __gcd(a, b)
{
if (b == 0n)
return a;
return __gcd(b, a % b);
}
function lcm (a, b)
{
let s = BigInt(a);
let s1 = BigInt(b);
let mul = s * s1;
let gcd = __gcd(s, s1);
let lcm = (mul - (mul % gcd)) / gcd;
return lcm;
}
let a = "36594652830916364940473625749407" ;
let b = "448507083624364748494746353648484939" ;
console.log(lcm(a, b));
|
Output:
443593541011902763984944550799004089258248037004507648321189937329