I initially tried using prime factorization. I spent quite a while banging my sleep deprived head against the wall of bad recursion methods before calling it a night. Today I wanted to try a different method instead (after I figured this out , I went back and tried the Euclid Method too (more straightforward) but that’s not relevant).
This is dirty, but how dirty I’m curious. Has anyone else tried the Table Method? I keep seeing Euclid or Prime Factorization so far.
I got so deep in this, I don’t really have any self-critical perspective. Just nice to have finally broken through.
function smallestCommons(arr) {
arr = arrayGenerate(arr);
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
var primesIndex = 0;
var currentPrime = 2;
var factorsArr = [];
var tempPrime = false;
while (primesIndex < primes.length - 1){
currentPrime = primes[primesIndex];
//if any of the numbers can be evenly divided, replace its original value with the result
arr = arr.map(function(val){
if (val % currentPrime === 0){
tempPrime = true;
return val/currentPrime;
} else {
return val;
}
});
//check if any of the numbers were able to be evenly divided and save the factor
//ALSO don't increment prime divisor, repeat with same instead
if (tempPrime === true){
factorsArr.push(currentPrime);
tempPrime = false;
continue;
}
//check if all numbers have been reduced to 1 (lowest factor) which means all factors found
if (arr.reduce(function(a,b){
return a * b;
}) === 1){
break;
} else {
primesIndex++;
}
}
return factorsArr.reduce(function(a,b){
return a*b;
});
}
//create array of numbers between two args (1 removed for being unnecessary)
function arrayGenerate(arr){
var newArr = [];
arr.sort(function(a,b){
return a-b;
});
if (arr[0] === 1){
arr[0] = 2;
}
for (var i = arr[0]; i <= arr[1]; i++){
newArr.push(i);
}
return newArr;
}
smallestCommons([1, 5]);