I have an lcm function that is failing for very large numbers, but not smaller numbers. For example, on an input of (6, 8), it returns 24 as the lcm. But if I do something such as (2000000000,1999999999), my while loop will infinitely loop, and not return anything.
I am using a big integer library to handle big numbers, but it doesn't seem to be working. Here is the code:
function lcm(n1, n2) {
n1 = bigInt(n1).value; //bigInt comes from the big-integer library
n2 = bigInt(n2).value;
let smaller = bigInt.min(n1, n2);
let bigger = bigInt.max(n1, n2);
let s1 = smaller;
if (smaller === 1) {
return bigger;
} else if (bigger === 1) {
return smaller;
}
while (s1 % bigger !== 0) { //once s1 % bigger is 0, we found the lcm in s1's variable
s1 = bigInt(s1).add(smaller);
console.log(s1);
}
return s1;
}
Any ideas?