user2406223 - 1 year ago 102
Javascript Question

# Project Euler #5 Javascript

This is the problem:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Here is my code:

``````var calculation = function(){
var result = 0;
for(var i = 20; i == 10000000000000; i++){
for(var e = 2; e == 20; e++){
if(i % e == 0){
result = i;
}
}
}
}
calculation();
``````

The problem is that the program just outputs
`0`
.

There are more graceful ways to solve this problem, but to address your current issue, the 'condition' portion of the `for`-loop needs to return `true` when you want to continue the loop, not when you want to stop it. So your `for` loops should look like this:

``````for(var i = 20; i <= 10000000000000; i++){
for(var e = 2; e <= 20; e++){
...
}
}
``````

Inside the loops, you've got another issue. You're setting `result` if `i % e == 0` but you've never defined a stop-case. In other words `result` will be the last number you which passed that test, even if it failed all the other tests for `i` and `e`. You'd have to do something like this:

``````for(var i = 20; i <= 10000000000000; i++){
bool found = true;
for(var e = 2; e <= 20; e++){
if (i % e != 0) {
found = false;
break; // stop testing other divisors
}
}
if (found) {
return i;
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download