问题是:
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?
这是我的代码:
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;
}
}
}
alert(result);
}
calculation();
问题是程序只输出0
。
最佳答案
有更优雅的方法来解决这个问题,但要解决您当前的问题,for
循环的“条件”部分需要返回 true
,当您想要继续循环,而不是当你想停止它时。所以你的 for
循环应该是这样的:
for(var i = 20; i <= 10000000000000; i++){
for(var e = 2; e <= 20; e++){
...
}
}
在循环内部,您遇到了另一个问题。您正在设置 result
if i % e == 0
但您从未定义停止情况。换句话说,result
将是您通过该测试的最后一个数字,即使它未通过 i
和 e
的所有其他测试。你必须做这样的事情:
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;
}
}
关于javascript - 欧拉计划 #5 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177774/