Smallest Common Multiple - can somebody explain why my code doesn't work?

``````function smallestCommons(arr) {
let big = 1;
let num=1;
let small=0;
let flag=0;
let result=0;
if (arr[0]>arr[1]) {
big=arr[0];
small=arr[1];
}
else big=arr[1]; small=arr[0];
console.log(small);
for(let i =small; i<=big; i++) {
num*=i;
}
console.log(num);
for (let j=num; j>=small; j--){
for(let i =small; i<=big; i++) {
if(j%i==0) flag++;
}
if(flag===big) result=j;
flag=0;
console.log(result);
}
return result;
}

console.log(smallestCommons([2,4]));

``````

I haven’t had time to fully review your code. BUT see this error in response to your second for loop

j is decreasing; i don’t understand why there would be an infinite loop

``````let j=num; j>=small; j--
``````

``````function smallestCommons(arr) {
let big=1;
let num=1;
let small=0;
let flag=0;
let result=0;

// Find biggest and smallest in range
if (arr[0]>arr[1]) {
big=arr[0];
small=arr[1];
} else {
// If you don't put {} around this, only the first will be guarded by the else.
big=arr[1];
small=arr[0];
}
// Log smallest value
console.log(small);

// Find product of all numbers in the range
for (let i=small; i<=big; i++) {
num*=i;
}
// Log product
console.log(num);

// Find smallest common multiple
// Note: why not start small and stop when you find the first common multiple? This way will take a *very* long time, especially when the range or numbers are big.
// Also Note: Why decrement by 1? If j % big === 0, then you won't have (j - 1) % big === 0 unless big === 1. I'd decrement by a different (bigger) number than 1.
for (let j=num; j>=small; j--) {
// Flag if the number is divisible by a value in the range
for (let i=small; i<=big; i++) {
if (j%i==0) {
flag++;
}
}
// Check if 'big' flags have been set
// Note: Can you have 'big' flags set? In the example you could have a flag for 2, 3, and 4. But that is 3 flags and big === 4.
if (flag===big) {
result=j;
}
// Reset flag and log
flag=0;
console.log(result);
}
return result;
}

// Test the function
console.log(smallestCommons([2,4]));
``````

Your code has some serious efficiency problems, which will trigger the infinite loop protections.

it works for the first three tests in the task; thank you though

I just fixed the issues I highlighted and with those fixes your code will pass for all tests. (Provided that you comment out the `console.log()`s.)