Skip to content

Instantly share code, notes, and snippets.

@crouch74
Created May 30, 2015 01:02
Show Gist options
  • Save crouch74/2f45fb4d50012618486e to your computer and use it in GitHub Desktop.
Save crouch74/2f45fb4d50012618486e to your computer and use it in GitHub Desktop.
calculate LCM using javascript reduce and recursive GCD calculator
function smallestCommons(arr) {
range = findRange(arr);
return calcRangeLCM(range);
}
function findRange(arr){
//arr=[1,5] ==> res=[1,2,3,4,5]
var res = [];
var min = Math.min.apply(null,arr);
var max = Math.max.apply(null,arr);
for(var i = min; i <=max;i++){
res.push(i);
}
return res;
}
function calcRangeLCM(range){
return range.reduce(function(c,l){
return calcLCM(c,l);
},1);
}
function calcLCM(a,b){
return a * b / calcGCD(a,b);
}
function calcGCD(a,b){
if ( ! b) {
return a;
}
return calcGCD(b, a % b);
}
smallestCommons([1,5]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment