简体   繁体   English

JavaScript-最大公约数-陷入无限循环

[英]JavaScript - Greatest common divisor - stuck in infinite loop

I am writing a function to computer the greatest common divisor for multiple numbers and I am stuck in this infinite while loop: 我正在编写一个函数来计算多个数字的最大公约数,并且陷入了这个无限的while循环中:

const gcd = (...nums) => {
    let answer = Math.min.apply(null, nums);
    while (answer > 0) {
        for (let index in nums) {
            if (nums[index] % answer !== 0) {
                answer--;
                break;
            } else if (index === (nums.length-1)){
               return answer;
            }
        }
    }
}

gcd(20, 155, 30)

For my test case on the last line, I was able to get to 5, which is the correct answer. 对于最后一行的测试用例,我能够达到5,这是正确的答案。 But it seems like once the answer gets to 5, I am not able to get to the if nor the else if statement and I am stuck in the infinite while loop. 但是,似乎答案一旦达到5,就无法到达if或else if语句,并且陷入无限的while循环中。

Any pointers? 有指针吗?

You can replace for in loop with simple for loop. 您可以用简单的for循环替换for in循环。 Don't use for in loop for iterating over arrays. 不要for in循环中使用for in遍历数组。

 const gcd = (...nums) => { let answer = Math.min.apply(null, nums); while(answer > 0) { for (let index = 0; index < nums.length; index++) { if (nums[index] % answer !== 0) { answer--; break; } else if (index === (nums.length-1)){ return answer; } } } } console.log(gcd(20, 155, 30)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM