Smallest Common Multiple JS Problem

Smallest Common Multiple JS Problem
0

#1

Hi, I’m trying to solve this problem in JS which is present in Intermediate Algorithm Scripting. I’m getting correct answers in my browser console, but freeCodeCamp tells me a Wrong Answer for higher inputs.

Please check my code and tell me why is this happening ?

``````function smallestMultiple(arr) {
var max = Math.max(arr[0],arr[1]);
var min = Math.min(arr[0],arr[1]);
var a = [];
for(var i=min;i<=max;i++)
a.push(i);
var result = 0;
for(var j=a[a.length-1];j<=100000000;j++) {
var c = 0;
for(var i=0;i<a.length;i++) {
if(j%a[i]===0)
c++;
}
if(c==a.length) {
result = j;
break;
}
}
return result;
}

``````

#2

I think its due to your second for loop.

you can write // noprotect as the first line of your function and it should work.

also, one thing i noticed that may make your code a little more efficient and help with the //noprotect issue is that you are looping for each number, since it has to be a multiple of the largest number you can increase your j by your largest argument instead of just 1

`for(var j=a[a.length-1];j<=100000000; j+max)`

#3

It worked. Thanks !!!