How to find the least common multiple of a range of numbers?

前端 未结 14 1687
一个人的身影
一个人的身影 2020-12-08 08:32

Given an array of two numbers, let them define the start and end of a range of numbers. For example, [2,6] means the range 2,3,4,5,6. I want to write javascrip

14条回答
  •  攒了一身酷
    2020-12-08 08:37

    How about:

    // Euclid Algorithm for the Greatest Common Denominator
    function gcd(a, b) {
        return !b ? a : gcd(b, a % b);
      }
      // Euclid Algorithm for the Least Common Multiple
    
    function lcm(a, b) {
        return a * (b / gcd(a, b));
      }
      // LCM of all numbers in the range of arr = [a, b];
    
    function smallestCommons(arr) {
      var i, result;
      // large to small - small to large
      if (arr[0] > arr[1]) {
        arr.reverse();
      } // only happens once. Means that the order of the arr reversed.
      for (i = result = arr[0]; i <= arr[1]; i++) { // all numbers up to arr[1] are arr[0].
        result = lcm(i, result); // lcm() makes arr int an integer because of the arithmetic operator.
      }
      return result;
    }
    smallestCommons([5, 1]); // returns 60

提交回复
热议问题