Hi everyone
So I’ve been doing the Intermediate Algorithm Scripting: Smallest Common Multiple and I almost got it. I’m passing all tests except the last one. I think the problem is that the code I wrote gives me a potential infinite loop message, which might be stopping it before it actually reaches the solution of the last test …? Since it is a very large number.
I’ve looked at other threads about the same problem but could find a solution Everyone was saying to make the algorithm less “brute-force” but I can’t figure out a good way to do it.
So how can I refine this code so that I don’t get this error anymore? I know that it’s not very elegant but it’s the only way I could think of to make it work. I kinda suck at math problems like these
Thanks in advance and have a nice day!
Happy coding
Your code so far
function smallestCommons(arr) {
let num = 1, i = 1;
let foundSolution = false;
let extArray = arr[0] < arr[1] ? Array.from({length: arr[1] - arr[0] + 1}, (a, b) => arr[0] + b) : Array.from({length: arr[0]-arr[1] + 1}, (a, b) => arr[0] - b);
while(foundSolution == false) {
let counter = 0;
for(i in extArray) {
if(num % extArray[i] === 0) {
counter++;
}
if(counter >= extArray.length) {
foundSolution = true;
return num;
}
}
num++;
}
}
console.log(smallestCommons([23,18]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36
.
Challenge: Smallest Common Multiple
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple