JavaScript 计算两个或三个数字的 LCM

new*_*015 2 javascript math jquery

我正在使用以下代码来确定两个或三个数字的 GCD:

$('#calc').click(function(){

Math.GCD = function(numbers) {
  for (var i = 1 ; i < numbers.length ; i++){
    if (numbers[i] || numbers[i] === 0)
      numbers[0] = twogcd(numbers[0], numbers[i]);
  }
  return numbers[0];

  function twogcd(first, second) {
    if (first < 0) first = -first;
    if (second < 0) second = -second;
    if (second > first) {var temp = first; first = second; second = temp;}
    while (true) {
        first %= second;
        if (first == 0) return second;
        second %= first;
        if (second == 0) return first;
    }
   }
};

Math.LCM = function(first,second) {
    return first * (second / this.GCD(first, second)); // CANNOT FIGURE OUT HOW TO EXTEND THIS TO THREE #s
};

var first   = document.getElementById("first").value;
var second   = document.getElementById("second").value;
var third = document.getElementById("third").value;

var numbers = [first,second,third];

var GCDresult = Math.GCD(numbers);


alert(GCDresult);
});
Run Code Online (Sandbox Code Playgroud)

注意那里关于 LCM 的功能。

这是我的 HTML:

<FORM NAME="sci-calc" method="POST" id="sci-calc">

<button TYPE="button" ID="calc">CALC</button>
<input type="text" name="stuff[]" class="input-field" id="first"/>
<input type="text" name="stuff[]" class="input-field" id="second"/>
<input type="text" name="stuff[]" class="input-field" id="third"/>

</FORM>
Run Code Online (Sandbox Code Playgroud)

还有一个小提琴:https : //jsfiddle.net/59z28rpk/

我正在尝试扩展此函数,以便它可以计算相同的两个或三个用户提供的输入的 LCM,但我终其一生都无法做到这一点。我是 JavaScript 的新手,希望得到任何帮助。请注意,如果一个字段留空,它也应该从计算中省略,就像对 GCD 所做的那样。

Ori*_*iol 6

您可以使用以下功能:

function gcd2(a, b) {
  // Greatest common divisor of 2 integers
  if(!b) return b===0 ? a : NaN;
  return gcd2(b, a%b);
}
function gcd(array) {
  // Greatest common divisor of a list of integers
  var n = 0;
  for(var i=0; i<array.length; ++i)
    n = gcd2(array[i], n);
  return n;
}
function lcm2(a, b) {
  // Least common multiple of 2 integers
  return a*b / gcd2(a, b);
}
function lcm(array) {
  // Least common multiple of a list of integers
  var n = 1;
  for(var i=0; i<array.length; ++i)
    n = lcm2(array[i], n);
  return n;
}
Run Code Online (Sandbox Code Playgroud)