-
-
Save crouch74/2f45fb4d50012618486e to your computer and use it in GitHub Desktop.
calculate LCM using javascript reduce and recursive GCD calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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