代码之家  ›  专栏  ›  技术社区  ›  newbie2015

在JavaScript中迭代GCD函数

  •  0
  • newbie2015  · 技术社区  · 9 年前

    我使用这个JavaScript函数来确定从输入字段获得的两个值的GCD:

    Math.GCD = function(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;
        }
    };
    

    如果用户在第三个输入字段中输入一个数字(否则,用户将输入两个数字并根据此函数计算),我想扩展此功能来计算三个数字的GCD。由于对JavaScript相对较新,我不确定如何将此函数扩展为三个值。有人能帮忙吗?

    小提琴: https://jsfiddle.net/tjj7won4/1/

    此外,我想以类似的方式确定LCM,正如在小提琴中观察到的那样,但我再次不确定如何扩展给定的函数。请帮帮我。

    2 回复  |  直到 9 年前
        1
  •  1
  •   guysigner    9 年前

    为任意数量的参数扩展函数 n ,只是循环 n-1 在一系列参数上的时间。

    这是因为在数学上 gcd(a,b,c) = gcd(a,gcd(b,c))

    用法: var GCDresult = Math.GCD([16,222,70]); // result: 2 .

    // numbers is an array of numbers: ex. [15,20,35,170]
    Math.GCD = function(numbers) {
      for (var i = 1 ; i < numbers.length ; i++){
        // take the next number for GCD with the first, 
        // and store the result back in the first.
        numbers[0] = twogcd(numbers[0], numbers[i]);
      }
      return numbers[0];
    
      // following is your original GCD function
      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;
        }
       }
    };
    

    为GCD案例更新的JSFiddle是 here .

        2
  •  0
  •   loxxy    9 年前

    通过使用相同的函数,您可以拥有可以接受任意数量的参数的东西。

    您也可以扩展它: fiddle

    Math.GCDe = function() {
        var result = arguments[0];
            for (var i=1;i<arguments.length;i++) 
            result = this.GCD(result,arguments[i]);
        return result;
    }