Last active
March 30, 2018 10:40
-
-
Save nickihastings/7c259df263a835b2d230bb93cbcbe88b to your computer and use it in GitHub Desktop.
Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters. The range will be an array of two numbers that will not necessarily be in numerical order. e.g. for 1 and 3 - find the smallest common multiple of both 1 and 3 that is evenly…
This file contains 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) { | |
//sort the array ascending, so that a is always the smaller number | |
arr.sort(function(a,b){ | |
return a-b; | |
}); | |
//first find the GCD of the pair of numbers using the Euclidean Algorithm. | |
//return the GCD | |
function gcd(a, b){ | |
var x = a; | |
var y = b; | |
//on subsequent calls, switch the numbers if they're not ascending. B is the bigger number. | |
if(a > b){ | |
x = b; | |
y = a; | |
} | |
//check if any are zero. If one is zero the other is the GCD | |
if(x == 0 ){ | |
return y; | |
} | |
if(y == 0){ | |
return x; | |
} | |
//run the Euclid algorithm, runs until the remainder is zero, swapping the numbers so | |
//that the remainder replaces x. | |
var r = y % x; | |
while(r !== 0){ | |
y = x; | |
x = r; | |
r = y % x; | |
} | |
return x; | |
} | |
//find the LCM of pairs of numbers, clever algorithm once you have found the GCD of the pair. | |
function lcm(a,b){ | |
return (a * b) / gcd(a,b); | |
} | |
//loop through the numbers in the range to find the LCM of all the numbers. | |
//use the LCM of the first pair to find the LCM of that and the next number, this | |
//reduces the numbers until all numbers are tested | |
for(var i = arr[0]; i <= arr[1]; i++){ //min and max numbers in the range. | |
var a, b, scm; | |
if(i == arr[0]){ | |
a = i; | |
} | |
else{ | |
a = scm; | |
} | |
b = i + 1; | |
//when you reach the max range return the lowest common multiple. | |
if(i == arr[1]){ | |
return scm; | |
} | |
//otherwise continue the loop. | |
scm = lcm(a,b); | |
} | |
} | |
smallestCommons([1,5]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment