Forked from anonymous/bonfire-smallest-common-multiple.js
Created
December 9, 2015 14:28
-
-
Save patrickcurl/fd6c9d2faa34085b403b to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/patrickcurl 's solution for Bonfire: Smallest Common Multiple
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
// Bonfire: Smallest Common Multiple | |
// Author: @patrickcurl | |
// Challenge: http://www.freecodecamp.com/challenges/bonfire-smallest-common-multiple | |
// Learn to Code at Free Code Camp (www.freecodecamp.com) | |
function smallestCommons(arr) { | |
range = toRange(arr); | |
return range.reduce(function(a, b) { | |
return lcm(a, b); | |
}); | |
} | |
function lcm(a, b) | |
{ | |
return (Math.abs(a * b) / gcd(a, b)); | |
} | |
function gcd(a, b) { | |
var temp; | |
while (b != 0) { | |
temp = b; | |
b = a % b; | |
a = temp; | |
} | |
return a; | |
} | |
function toRange(arr){ | |
var r = []; | |
var end = arr.reduce(function(a,b){ | |
return Math.max(a,b); | |
}); | |
var start = arr.reduce(function(a, b) { | |
return Math.min(a, b); | |
}); | |
for (var i = start; i <= end; i++) { | |
r.push(i); | |
} | |
return r; | |
} | |
smallestCommons([1,5]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment