# Smallest Common Multiple - Confused why my answer isn't working

I am passing all the tests minus the last one.

Can someone please explain why? I’m unsure how to fix this - I tried even hard-coding the maximum value for x to be the final answer and it’s not working.

``````function smallestCommons(arr) {
// Sort from lowest to highest
arr.sort(function(a, b) {
return a - b;
});
// Function to create the reverse ordered arra
function createArray(array) {
let range = (array[1] - array[0]);
for (let i = 1; i < range; i++) {
array.splice(i,0,array[0]+i);
}
return arr.reverse();
}
// Calling function
createArray(arr);

// Startup values for while loop
let x = 1;
let count = 0
// Loop through 'x' until count reaches the length of the array
while(x) {
x++
for (let i = 0; i <= arr.length; i++) {
if (x % arr[i] == 0) {
count++
} else {
count = 0
}
if (count === arr.length) {
console.log(x)
return x
}
}
}
}

smallestCommons([2,10]);

``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36`.

Challenge: Smallest Common Multiple

It’s possible the function is timing out because you’re only incrementing `x` by 1 on each iteration of the loop. I changed your code so that `x` is incremented by `arr[0]` (which is the smallest number in the array) on each iteration because it’s a much more efficient way to do this than incrementing by only 1. Here’s the modified code that passes the test for me:

``````function smallestCommons(arr) {
// Sort from lowest to highest
arr.sort(function(a, b) {
return a - b;
});
// Function to create the reverse ordered arra
function createArray(array) {
let range = (array[1] - array[0]);
for (let i = 1; i < range; i++) {
array.splice(i,0,array[0]+i);
}
return arr.reverse();
}
// Calling function
createArray(arr);

// Startup values for while loop
let x = 0;
let count = 0
// Loop through 'x' until count reaches the length of the array
while(true) {
x+=arr[0];
for (let i = 0; i <= arr.length; i++) {
if (x % arr[i] == 0) {
count++
} else {
count = 0
}
if (count === arr.length) {
console.log(x)
return x
}
}
}
}

smallestCommons([2,10]);
``````
1 Like

Thank you so much! I really appreciate your help, I would not have got there myself. That makes a lot of sense though and is 100x more efficient.

1 Like