计算JavaScript中两个或三个数字的LCM [英] Calculate the LCM of two or three numbers in JavaScript

查看:66
本文介绍了计算JavaScript中两个或三个数字的LCM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the following code to determine the GCD of two or three numbers:

$('#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);
});

请注意此处有关LCM的功能.

notice the function in there about the 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>

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

我正在尝试扩展此功能,以便它可以计算相同的两个或三个用户提供的输入的LCM,但我终生无法正确使用它.我是JavaScript的新手,希望对您有所帮助.请注意,如果将字段保留为空白,则也应该像GCD一样将其从计算中省略.

I am trying to extend this function so that it can compute the LCM of the same two or three user supplied inputs, but I cannot for the life of me get it right. I am a novice at JavaScript and would appreciate any help whatsoever. Note that if a field is left blank it should be omitted from the calculation also, as is done for the GCD.

推荐答案

您可以使用以下功能:

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;
}

这篇关于计算JavaScript中两个或三个数字的LCM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆