javascript - How to find the least common multiple of a range of numbers? -
given array of 2 numbers, let them define start , end of range of numbers. example, [2,6]
means range 2,3,4,5,6. want write javascript code find least common multiple range. code below works small ranges only, not [1,13]
(which range 1,2,3,4,5,6,7,8,9,10,11,12,13), causes stack overflow. how can efficiently find least common multiple of range?
function leastcommonmultiple(arr) { var minn, max; if ( arr[0] > arr[1] ) { minn = arr[1]; max = arr[0]; } else { minn = arr[0]; max = arr[1]; } function repeatrecurse(min, max, scm) { if ( scm % min === 0 && min < max ) { return repeatrecurse(min+1, max, scm); } else if ( scm % min !== 0 && min < max ) { return repeatrecurse(minn, max, scm+max); } return scm; } return repeatrecurse(minn, max, max); }
i think gets job done.
function leastcommonmultiple(min, max) { function range(min, max) { var arr = []; (var = min; <= max; i++) { arr.push(i); } return arr; } function gcd(a, b) { return !b ? : gcd(b, % 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
Comments
Post a Comment