最小的多个javascript

时间:2014-01-06 21:53:40

标签: javascript lcm

我必须找到所有数字1到1的lcm,包括20,我想出了这段代码。它虽然效率低下,但也提出了比正确答案多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;
}

2 个答案:

答案 0 :(得分:1)

我的代码出了什么问题?

isDivisible一直执行,直到divisible设置为true(来自 while 循环),其中for循环将为您完成所有这些操作。此外,您将i+=2放入while循环中,在您的程序停止执行isDivisible这么多次之后,结果会增加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

答案 1 :(得分:0)

为了好玩:

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

当数组(alert)中包含的值是传递给回调的值的倍数(在本例中为[0, . . ., 6])时6应该{{1}}。请参阅Array.prototype.map()

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