Project Euler LCM of 1..20, with some guesswork I'm doing a Euler challenge that is stating to find the smallest positive number that is divisible (without a remainder) by all numbers from 1 to 20. So I did it however, I don't like the fact that I have to guess up to which number the while loop have to go (var s.... s &lt; 303000000) and I guess there are too many variables. I'm sure I could get rid of 's'. 

var s = 0;
var n = 1;

while (s &lt; 303000000) {
        for (var i=1;i&lt;21;i++) {
                if (n % i != 0) {
                        break;
                }
                if (i == 20) {
                        console.log(n);
                }
        }
        n += 1;
        s += 1;
}
The below formula can be used to get the LCM of two numbers. See Reduction by the greatest common divisor section in Wikipedia

               a * b
lcm(a, b) = ―――――――――――
             gcd(a, b)


GCD can be calculated by using the Euclidean AlgorithmSee Using Euclid's algorithm section in Wikipedia.

gcd(a, b) = gcd(b, a % b)


Using these two formulas, the LCM can be calculated as follow



console.time('new');

function gcd(a, b) {
    while (b !== 0) {
        var temp = a;
        a = b;
        b = temp % b;

        // Can be written in ES6 as
        // [a, b] = [b, a % b];
    }

    return a;
}

function lcm(a, b) {
    return a * b / gcd(a, b);
}
var range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
console.log(range.reduce(lcm, 1));
console.timeEnd('new');




This is very efficient than using while and for, see this JsFiddle demo.

Note: This answer is inspired by this and this posts.