0

我必须找到所有数字 1 到 20 的 lcm,然后我想出了这个代码。它虽然效率低下,但也给出了比正确答案多 2 的答案。谁能告诉我为什么?

//variable used to shut off the while loop.
divisable = false;

var i = 2;

//function to prove if the number is a lcm

var isDivisable = function(number){
    for(var i = 2; i<=20; i++){
        if(number%i !== 0){
            divisable = false;
            //  added the break to shut down the function, 
            //  as no other loops need to be counted
            break;
        }else{
            divisable = true;
        }
    }
};    


while(!divisable){
    isDivisable(i);

    i+=2;
}
4

2 回答 2

1

我的代码有什么问题?

isDivisible一直执行,直到divisible设置为 true(从您的while循环),您的for循环将为您完成所有这些工作。此外,i+=2在您的程序停止执行isDivisible这么多次后,您将放入 while 循环,该循环将结果添加 2。

怎么修?

删除while循环,然后isDivisable手动调用。

var isDivisable = function(number){
    if (number % 1 == 0) {
    for(var i = 2; i<=20; i++){
        if(number%i !== 0){
            divisable = false;
            //  added the break to shut down the function, 
            //  as no other loops need to be counted
            break;
        }else{
            divisable = true;
            alert(i);
        }
    }else
    {
        alert('Your number is not divisible.');
    }
};    

isDivisable(6); //Replace with a number

结果i将是倍数。

补充说明

isDivisible在您的代码中拼写错误,如isDivisable.

于 2014-01-06T22:03:46.993 回答
0

为了娱乐:

[0, 1, 2, 3, 4, 5, 6].map(function(i) {
    if(this % i == 0)
        alert(i);
}, 6);

应该alert在数组 ( [0, . . ., 6]) 中包含的值是传递给回调的值的倍数时(在这种情况下6)。见Array.prototype.map()

http://jsfiddle.net/5nSE4/1/

于 2014-01-06T22:30:07.920 回答