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

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

    As this question has recently been revived, here's what I think is a simpler take on the question, writing very simple helper functions to calculate the greatest common divisor of two integers (gcd), to calculate the least common multiple of two integers (lcm), to calculate the least common multiple of an array of integers (lcmAll), to generate the range of integers between two given integers (rng), and finally, in our main function, to calculate the least common multiple of the range of integers between two given integers (lcmRng):

    const gcd = (a, b) => b == 0 ? a : gcd (b, a % b)
    const lcm = (a, b) =>  a / gcd (a, b) * b
    const lcmAll = (ns) => ns .reduce (lcm, 1)
    const rng = (lo, hi) => [...Array (hi - lo + 1)] .map ((_, i) => lo + i)
    
    const lcmRng = (lo, hi) => lcmAll (rng (lo, hi))
    
    console .log (lcmRng (1, 13))

    All of these functions are simple. Although the question was tagged recursion, only gcdis recursive. If this is an attempt to play with recursion, we could rewrite lcmAll in a recursive manner with something like this:

    const lcmAll = (ns) => 
      ns.length == 0 
        ? 1 
        : lcm(ns[0], lcmAll(ns .slice (1)))
    

    Although I'm a big fan of recursion, I see no other reason to choose the recursive version here over the reduce one. In this case, reduce is cleaner.

    And finally, if you really want the API originally requested where the range bounds are passed in an array, you could write one more wrapper:

    const leastCommonMultiple = ([lo, hi]) => lcmRng (lo, hi)
    
    leastCommonMultiple ([1, 13]) //=> 360360
    
    0 讨论(0)
  • 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]);

    0 讨论(0)
  • 2020-12-08 08:45
    function range(min, max) {
      var arr = [];
      for (var i = min; i <= max; i++) {
        arr.push(i);
      }
      return arr;
    }
    
    function gcd (x, y) {
      return (x % y === 0) ? y : gcd(y, x%y);
    }
    
    function lcm (x, y) {
      return (x * y) / gcd(x, y); 
    }
    
    function lcmForArr (min, max) {
      var arr = range(min, max);
      return arr.reduce(function(x, y) {
        return lcm(x, y); 
      });
    }
    
    range(10, 15); // [10, 11, 12, 13, 14, 15]
    gcd(10, 15); // 5
    lcm(10, 15); // 30
    lcmForArr(10, 15); //60060
    
    0 讨论(0)
  • 2020-12-08 08:55

    LCM function for a range [a, b]

    // Euclid algorithm for Greates Common Divisor
    function gcd(a, b)
    { 
    	return !b ? a : gcd(b, a % b);
    } 
    
    // Least Common Multiple function
    function lcm(a, b) 
    {
    	return a * (b / gcd(a,b));
    }
    
    // LCM of all numbers in the range of arr=[a, b] 
    function range_lcm(arr)
    {
    	// Swap [big, small] to [small, big]
    	if(arr[0] > arr[1]) (arr = [arr[1], arr[0]]);
    
    	for(x = result = arr[0]; x <= arr[1]; x++) {
    		result = lcm(x, result);
    	}
    	
    	return result; 
    }
    
    alert(range_lcm([8, 5])); // Returns 840

    0 讨论(0)
  • 2020-12-08 08:55
     function leastCommonMultiple(arr) {
        /*
          function range(min, max) {
            var arr = [];
           for (var i = min; i <= max; i++) {
            arr.push(i);
          }
           return arr;
        }
        */
        var min, range;
         range = arr;
        if(arr[0] > arr[1]){
           min = arr[1];
        }
        else{
           min = arr[0]
        }
    
        function gcd(a, b) {
            return !b ? a : gcd(b, a % b);
        }
    
        function lcm(a, b) {
            return (a * b) / gcd(a, b);   
        }
    
       var multiple = min;
        range.forEach(function(n) {
           multiple = lcm(multiple, n);
        });
    
       return multiple;
    }
    

    console.log( leastCommonMultiple([1, 13]) )

    0 讨论(0)
  • 2020-12-08 08:56

    Mine is not as fancy as the other answers but I think it is easy to read.

    function smallestCommons(arr) {
    	//order our array so we know which number is smallest and which is largest
    	var sortedArr = arr.sort(sortNumber),
    	//the smallest common multiple that leaves no remainder when divided by all the numbers in the rang
    	smallestCommon = 0,
    	//smallest multiple will always be the largest number * 1;
    	multiple = sortedArr[1];
    
    	while(smallestCommon === 0) {
    		//check all numbers in our range
    		for(var i = sortedArr[0]; i <= sortedArr[1]; i++ ){
    			if(multiple % i !== 0 ){
    				//if we find even one value between our set that is not perfectly divisible, we can skip to the next multiple
    				break;
    			}
    
    			//if we make it all the way to the last value (sortedArr[1]) then we know that this multiple was perfectly divisible into all values in the range
    			if(i == sortedArr[1]){
    				smallestCommon = multiple;
    			}
    
    		}
    
    		//move to the next multiple, we can just add the highest number.
    		multiple += sortedArr[1];
    	}
    
    	console.log(smallestCommon);
    	return smallestCommon;
    }
    
    function sortNumber(a, b) {
        return a - b;
    }
    
    
    smallestCommons([1, 5]); // should return 60.
    smallestCommons([5, 1]); // should return 60.
    smallestCommons([1, 13]); // should return 360360.
    smallestCommons([23, 18]); // should return 6056820.

    Edit: Turned answer into snippet.

    0 讨论(0)
提交回复
热议问题