Last active
July 13, 2020 22:53
-
-
Save obritoluis/c1ea58db960f86b92b9681a4c67ac144 to your computer and use it in GitHub Desktop.
freeCodeCamp: Intermediate Algorithm Scripting: 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
function smallestCommons(arr) { | |
let firstNum = arr[0], | |
secondNum = arr[1], | |
primeFactors = [[],[]], //save the prime factors here | |
divider = 2, // start diving by two | |
counts = [{},{}]; //count how many times each prime factor appears | |
//get the firsNum prime factors | |
while (firstNum > 1) { | |
if (firstNum % divider === 0) { | |
primeFactors[0].push(divider); | |
firstNum = firstNum / divider; | |
divider = 2; | |
} else { | |
divider++ | |
} | |
} | |
//get the secondNum prime factors | |
while (secondNum > 1) { | |
if (secondNum % divider === 0) { | |
primeFactors[1].push(divider); | |
secondNum = secondNum / divider; | |
divider = 2; | |
} else { | |
divider++ | |
} | |
} | |
//get the counts of each prime factor | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = 0; j < primeFactors[i].length; j++) { | |
let num = primeFactors[i][j]; | |
counts[i][num] = counts[i][num] ? counts[i][num] + 1 : 1; | |
} | |
} | |
//merge both counts. when there are common numbers, drop the smaller one | |
function extend(obj, src) { | |
//iterate between each src key | |
Object.keys(src).forEach(function(key) { | |
// if obj doesn't have this property | |
if (!obj.hasOwnProperty(key)) { | |
// add the key: value | |
obj[key] = src[key]; | |
} else { | |
// if obj property value is bigger than src property value, saves the former, else saves the latter | |
obj[key] = obj[key] > src[key] ? obj[key] : src[key]; | |
} | |
}); | |
return obj; | |
} | |
let multiples = extend(counts[0], counts[1]); | |
//calculate the smallest common multiple | |
let scm = 1; | |
Object.keys(multiples).forEach(function(key) { | |
scm *= Math.pow(key, multiples[key]); | |
}); | |
console.log(scm); | |
// iterate between the arr range | |
let arrRange = []; | |
for (let i = arr[0]; i <= arr[1]; i++) { | |
arrRange.push(i); | |
} | |
//divide the scm by each value in the range, if it cannot be evently divided, multiply by two, and keep until it gets the right result | |
let value = arr[0], | |
stop = false; | |
while (value <= arr[1]) { | |
if (scm % value === 0) { | |
if (value === arr[1]) { | |
console.log(scm); | |
} | |
console.log(value); | |
value++; | |
} else { | |
value = arr[0]; | |
scm = scm * 2; | |
} | |
} | |
return arr; | |
} | |
smallestCommons([2, 10]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment