简体   繁体   English

Google Chrome开发者工具在嵌套for循环中不一致

[英]Google chrome developer tool is inconsistent in nested for loop

While trying to solve this project euler problem (using Google chrome - snippets feature in developer tools to code and execute) , I encountered a strange behavior. 尝试解决此项目欧拉问题时 (在开发人员工具中使用Google chrome-代码段功能进行编码和执行),我遇到了奇怪的行为。

var palFound = false;
isPal = function (word) {
    var wordCount = word.length;
    for (i = 0; i < wordCount; i++) {
        if (word[i] != word[wordCount - i - 1]) {
            return false;
        }
    }
    return true;
}

for (var k = 999; k >= 100; k--) {
    for (var j = 999; j >= 100; j--) {
        var prod = k * j,
            prodString = prod + '';
        if (isPal(prodString)) {
            console.log(prod, k, j);
            palFound = true;
            break;
        }

    }
    if (palFound) {
        break;
    }
}

Above code should ideally display the first encountered palindrome product and should break.But when executed the above code displays a wrong answer 580085 which is a product of 995 and 583. 上面的代码在理想情况下应该显示第一个遇到的回文乘积,并且应该折断。但是执行时,上面的代码显示错误的答案580085,这是995和583的乘积。

But when the for loops limit are changed to 999 to 900 (as shown below), correct answer is displayed - 906609 which is a product of 993 and 913. 但是,当for循环限制更改为999到900(如下所示)时,将显示正确的答案-906609,它是993和913的乘积。

for(var k=999;k >=900;k--){
for(var j=999;j>=900;j--)

ideally, 993 and 913 should be encountered first, instead of 995 and 583. I am curious to know why is this happening?. 理想情况下,应该首先遇到993和913,而不是995和583。我很好奇这是为什么发生的?

For each k value in your outer loop your inner loop counts down from 999 to 100, so when k is 995 then j counts down to 583 finds a palindrome and the code breaks out of your loop. 对于外循环中的每个k值,您的内循环从999递减到100,因此当k为995时,j递减到583会找到回文,并且代码会退出循环。

When you amend j to only count down to 900 it does not reach 583 and so the first palidrome you now reach is 993 * 913. 当您将j修改为仅递减到900时,它不会达到583,因此您现在到达的第一个教区是993 * 913。

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

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