简体   繁体   English

Javascript最小公倍数函数失败

[英]Javascript least common multiple function is failing for very large numbers

I have an lcm function that is failing for very large numbers, but not smaller numbers. 我有一个lcm函数,但对于很大的数字却失败了,但对于较小的数字却失败了。 For example, on an input of (6, 8), it returns 24 as the lcm. 例如,在输入(6,8)上,它返回24作为lcm。 But if I do something such as (2000000000,1999999999), my while loop will infinitely loop, and not return anything. 但是,如果我执行(2000000000,1999999999)之类的操作,则while循环将无限循环,并且不返回任何内容。

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? 有任何想法吗?

Your algorithm is too slow. 您的算法太慢。 With n1=2000000000 and n2=1999999999 it is doing 2 billion add calls. n1=2000000000n2=1999999999它正在进行20亿次add呼叫。 You can use this formula: 您可以使用以下公式:

lcm(a, b) = a * b / gcd(a, b)

To calculate gcd(a, b) (greatest common divisor) you need to implement division-based version of Euclidian algorithm . 要计算gcd(a, b) (最大公约数),您需要实现基于除数的Euclidian算法 Recursive implementation: 递归实现:

function gcd(a, b) {
    return b == 0 ? a : gcd(b, a % b);
}

Other implementations (if you want to avoid recursion) can be found here: JS how to find the greatest common divisor 其他实现(如果要避免递归)可以在这里找到: JS如何找到最大的公约数

If you are using this package , then you are in luck - it has a built in lcm method for you: link to the docs 如果您使用的是此软件包 ,那么您很幸运-它具有内置的lcm方法供您使用: 链接至文档

If you want to see the implementation of it, check out the source over at the Github repository. 如果要查看其实现,请在Github存储库中查看源代码。

Implementation of the method inside the above library: Source 上述库中方法的实现:

Hope this helps you out :) 希望这可以帮助你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM