# Smallest Common Multiple

Hello,

I wrote a script for the Smallest Common Multiple project but it seems that isn’t working for bigger numbers.
Probably because the loop is taking too long.

Here is to code:

``````function smallestCommons(arr) {
arr.sort(function(a,b){
return a-b;
});

var s = arr;
var b = arr;

var idx = 1;
var found = false;

while(!found){
var k = 0;
for(s = arr; s<=b; s++){
if(idx%s === 0)
k++;
}

if(k === b)
break;

idx++;
}
return idx;
}

smallestCommons([1,13]);
``````

I know my logic is wrong. But this is what I could get up to this point! I know it works, but it gets stuck in the middle somewhere xD.

The best way to solve this is to study up on the euclidean algorithm a bit.
Its basically lcm(a, b) = gcd(a, b)/a * b

I’d advise you find the code for gcd for a start, then use it to find lcm.

This is what I did at the end… I’ve learned how it works with lcm and gcd P.S. It’s `lcm(a,b) = (a*b) / gcd(a,b)` as far as I know How I would do it now

``````Function lcm(a, b){
let i = a;
While(i<999999999){
If (I % b === 0) then {
Return I;
} else {
I += a;
}
}
Return "greater than 999999999";
}
``````

Celphone, forgive the changing case.

1 Like