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

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

    Hey I came across this page and wanted to share my solution :)

    function smallestCommons(arr) {
      var max = Math.max(arr[0], arr[1]),
          min = Math.min(arr[0], arr[1]),
          i = 1;
      while (true) {
        var count = 0;
        for (j = min; j < max; j++) {
          if (max * i % j !== 0) {
            break;
          }
          count++;
        }
        if (count === (max - min)) {
          alert(max * i);
          return max * i;
        }
        i++;
      }
    }
    smallestCommons([23, 18]);

提交回复
热议问题