Hello, I was solving this smallest common multiple challenge in the intermediate algorithm challenges and I went with following approach
function smallestCommons(arr) {
const small = Math.min(...arr),
big = Math.max(...arr);
if (small === 0 || big === 0) throw new Error('Dividing with 0 creates black holes');
let bool;
for (let i = 1; true; i++) {
bool = true;
for (let j = small; j <= big; j++) {
if (i % j !== 0) {
bool = false;
break;
}
}
if (bool) {
return i;
}
}
}
it passes first three tests, but cannot pass last two even tho it returns the expected answer, then I searched for other solutions and somehow they pass all of the
For example following solution isn’t mine and passes just fine
function smallestCommons2(arr) {
// Sort array from greater to lowest
// This line of code was from Adam Doyle (http://github.com/Adoyle2014)
arr.sort(function(a, b) {
return b - a;
});
// Create new array and add all values from greater to smaller from the
// original array.
var newArr = [];
for (var i = arr[0]; i >= arr[1]; i--) {
newArr.push(i);
}
// Variables needed declared outside the loops.
var quot = 0;
var loop = 1;
var n;
// Run code while n is not the same as the array length.
do {
quot = newArr[0] * loop * newArr[1];
for (n = 2; n < newArr.length; n++) {
if (quot % newArr[n] !== 0) {
break;
}
}
loop++;
} while (n !== newArr.length);
return quot;
}
Link to challenge