I finally solved the smallest common multiples challenge after a bit more than an hour, with the initial setup from yesterday of just the “between” array. It seems like a really long solution, but I also used the code from previous challenge (Summing All Primes) and I had to build additional function to solve the real challenge.
I would really appreciate any feedback! Don’t mind long commenting on the code, I was too excited I am doing this in around three weeks!
function smallestCommons(arr) {
var num1 = arr[0], num2 = arr[1], between = [], all = [], mult = [], res = 1;
// Creating an array of range between the numbers given
if (num1 < num2) {
for (var i = num1+1; i < num2; i++) {
between.push(i);
}
} else if (num1 > num2) {
for (var j = num1-1; j > num2; j--) {
between.push(j);
}
}
// Creating a decending array of numbers given + the range in between
between.unshift(num1);
between.push(num2);
all = between.sort(function(a,b) {
return b - a;
});
// Additiaonl function for checking if any element in arr (first argument) is divisible by divisor (second argument). God, I sound like FCC instructions.
function ifAnyDivisibleBySth(arr, divisor) {
var result;
for (var k = 0; k < arr.length; k++) {
if (arr[k] % divisor === 0) {
result = true;
break;
} else {
result = false;
}
}
return result;
}
// Function for getting primes, from previous challenge. Only this code is borrowed.
function getPrimes(max) {
var sieve = [], x, y, primes = [];
for (x = 2; x <= max; ++x) {
if (!sieve[x]) {
// x has not been marked -- it is prime
primes.push(x);
for (y = x << 1; y <= max; y += x) {
sieve[y] = true;
}
}
}
return primes;
}
// getting the necessary primes
var primesArray = getPrimes(all[0]);
// I actually built this stuff. I cannot believe this LOL
// To clear the probable confusion: We got all the primes in
// primesArray. We go through each prime (first for loop) and
// divide each element of "all" array with each prime as long
// as it can be divided evenly (while loop) and count the
// common multiples by adding them to "mult" array (second for loop).
for (prime = 0; prime < primesArray.length; prime++) {
while (ifAnyDivisibleBySth(all, primesArray[prime])) {
for (var n = 0; n < all.length; n++) {
if (all[n] % primesArray[prime] === 0) {
all[n] /= primesArray[prime];
}
}
mult.push(primesArray[prime]);
}
}
// When we counted the multiples correctly, it's easy. We just do a multiplication of all of them to get the least common multiple.
// PS Easy? This for loop was so complicated for me just two weeks ago! LOL
for (var f = 0; f < mult.length; f++) {
res *= mult[f];
}
return res;
}