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

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

    I think this gets the job done.

    function leastCommonMultiple(min, max) {
        function range(min, max) {
            var arr = [];
            for (var i = min; i <= max; i++) {
                arr.push(i);
            }
            return arr;
        }
    
        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(min, max).forEach(function(n) {
            multiple = lcm(multiple, n);
        });
    
        return multiple;
    }
    
    leastCommonMultiple(1, 13); // => 360360
    

提交回复
热议问题