Last active
December 30, 2018 10:17
-
-
Save NouranMahmoud/3247c6ac37ca41f46542cc23a1691940 to your computer and use it in GitHub Desktop.
Least Common Multiple (LCM)
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
// Least Common Multiple | |
function LCM(n, m, range) { | |
var list1 = []; | |
var list2 = []; | |
var match; | |
for(var i = 1; i <= range; i++) { | |
list1.push(n*i) | |
list2.push(m*i) | |
//compare two arrays, if there is a match this loop will break because this will be the LCM | |
var match = findMatch(list1, list2); | |
if(match !== 0) break; | |
} | |
return match; | |
} | |
// compare each item in the two arrays in the current state, and return the first match. | |
function findMatch(arr1, arr2) { | |
var num = 0; | |
for(var i = 0; i< arr1.length; i++) { | |
for( var y = 0; y < arr2.length; y++ ) { | |
if (arr1[i] === arr2[y]) { | |
num = arr1[i]; | |
break; | |
} | |
} | |
} | |
return num; | |
} | |
// To find the LCM with the Euclidean Algorithm like we can do with GCF. | |
// Just use the equation LCM(a, b) = (a*b)/GCF(a,b) | |
function LCM2(a, b){ | |
return (a*b)/GCF2(a,b) | |
} | |
// You can find the code bellow from this gist https://gist.github.com/NouranMahmoud/7c9cb828c43287b9a74f0085242fcba9 | |
function GCF2(num1, num2) { | |
var gcf = recursion(num1, num2); | |
return gcf; | |
} | |
function recursion(num1, num2) { | |
// the equation is num1 = Math.floor(num1/num2)*num2 + remainder; | |
// but I chanegd it to be able to store the remainder .. which will be our GCF. | |
var remainder = num1 - Math.floor(num1/num2)*num2; | |
// if remainder if 0, then we need the previous remainder which is num2 | |
if(remainder === 0) { | |
return num2; | |
} | |
num1 = num2; | |
num2 = remainder; | |
return recursion(num1, num2); // re calculate with the new values. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment