Here’s my solution to the Smallest Common Multiple intermediate algorithm challenge. It works, but it’s kind of long. I’m posting it to see if anyone can help me make it cleaner or shorter. The main idea is that the LCM needs just enough factors to create any of the numbers in the series. Thanks for any help!
// 1. sort array, smallest to largest
// 2. prime-factor all numbers from arr[0] to arr[1]
// 3. Make an array with all unique factors from the above
// problem: you need as many duplicate factors to make each number
// e.g. 4 requires 2,2
// 4 .multiply them
function smallestCommons(arr) {
var facArray = [],
lcmArray = [],
lcm = 1,
i, j, swap;
// Sort the given two number array
if ( arr[0] > arr[1] ) {
swap = arr[0];
arr[0] = arr[1];
arr[1] = swap;
}
// Make an array of each number's prime factors
for (i = arr[0]; i <= arr[1]; i++) {
facArray.push(primeFactorize(i));
}
// remove prior duplicates from each prime factor array
for (i = 0; i < facArray.length; i++) {
for (j = 0; j < i; j++) {
facArray[j].forEach(function(element) {
swap = facArray[i].indexOf(element);
if ( swap >= 0 ) {
facArray[i].splice(swap,1);
}
});
}
}
// concatenate the array
facArray.forEach(function(subArray) {
subArray.forEach(function(element) {
lcmArray.push(element);
});
});
// Multiply everything together
lcmArray.forEach(function(element) {
lcm *= element;
});
return lcm;
}
function getFactor(num) {
// returns the lowest factor
var i;
for (i = 2; i <= Math.sqrt(num); i++) {
if ( num%i === 0 ) return i;
}
return 1;
}
function primeFactorize(num) {
// returns an array of prime factors
var factor, factors = [];
while( (factor = getFactor(num)) > 1 ) {
factors.push(factor);
num = num/factor;
}
factors.push(num);
return factors;
}