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

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

    This is a non-recursive version of your original approach.

    function smallestCommons(arr) {
      // Sort the array
      arr = arr.sort(function (a, b) {return a - b}); // numeric comparison;
      var min = arr[0];
      var max = arr[1];
    
      var numbers = [];
      var count = 0;
    
      //Here push the range of values into an array
      for (var i = min; i <= max; i++) {
        numbers.push(i);
      }
      //Here freeze a multiple candidate starting from the biggest array value - call it j
      for (var j = max; j <= 1000000; j+=max) {
    
        //I increase the denominator from min to max
        for (var k = arr[0]; k <= arr[1]; k++) {
    
          if (j % k === 0) { // every time the modulus is 0 increase a counting 
            count++; // variable
          }
        }
    
        //If the counting variable equals the lenght of the range, this candidate is the least common value
        if (count === numbers.length) { 
          return j; 
        }
        else{
          count = 0; // set count to 0 in order to test another candidate
        }
      }
    }
    
    alert(smallestCommons([1, 5]));

提交回复
热议问题