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

前端 未结 14 1688
一个人的身影
一个人的身影 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 09:02

    function smallestCommons(arr) {
      var max = Math.max(...arr);
      var min = Math.min(...arr);
      var candidate = max;
    
      var smallestCommon = function(low, high) {
        // inner function to use 'high' variable
        function scm(l, h) {
          if (h % l === 0) {
            return h;
          } else {
            return scm(l, h + high);
          }
        }
        return scm(low, high);
      };
    
      for (var i = min; i <= max; i += 1) {
        candidate = smallestCommon(i, candidate);
      }
    
      return candidate;
    }
    
    smallestCommons([5, 1]); // should return 60
    smallestCommons([1, 13]); // should return 360360
    smallestCommons([23, 18]); //should return 6056820
    

提交回复
热议问题