0

该程序的目的是列出从 1 开始的所有素数。我是一个完全的新手。我开始用 C++ 写这个(不成功)并翻译成这个(JS)我知道一些问题,但不知道如何解决它们:处理全局变量、写替换、写之前没有超时等等。重要的是我使用外部 JS 文件?总之,我如何使这项工作?

<!doctype html>
<html>
<head>
<script>

var number = 3; //to be run through the prime test
var prime = [2]; //numbers found to be prime
var found = 1; //counter for primes found
var runs = 0; //counter for times number has been tested
//numbers are tested against all smaller found primes
function test()
{
    window.scroll(0,document.height); //automatically view the latest prime
    var line = document.createElement("div");
    while(runs < found && (prime[runs] < (number / 2))) //has number passed all tests
    {
        if(number % prime[runs] !== 0) //is number divisible by smaller prime
        {
            runs = runs + 1; //number passed a test
        }
        else //number is not prime
        {
            number = number + 1; //next number generated
            runs = 0; //reset test counter for next number
            setTimeout(test, 100); //start running next number tests
        }
    } //number passed all tests
line.innerHTML = number; //prime number displayed
document.body.appendChild(line);
prime[found] = number; //prime number saved for testing
found = found + 1; //counter for found is increased
number = number + 1; //next number generated
runs = 0; //reset test counter for next number
setTimeout(test, 100); //start running next number tests
}

</script>
</head>
<body>
<form>
    <input type="button" onclick="test()">
</form>
</body>
</html>
4

2 回答 2

0

需要注意的几点:

  1. for (runs < found)

    你似乎想要一个while循环for循环不能只包含一个条件。

  2. document.writeln()document完成加载并关闭后无法使用。在此之后使用它们将重新打开document,将其重置为空白。

    要在此之后修改 DOM,您需要使用innerHTMLordocument.createElement()element.appendChild()

    var line = document.createElement('div');
    line.innerHTML = number;
    document.body.appendChild(line);
    
  3. 为了避免无限递归并让 UI 线程有机会更新页面的显示,您可以在再次调用时使用计时器test

    setTimeout(test, 100);
    
于 2013-05-08T16:06:12.743 回答
0

在数学方面,

var prime = [1];

1不是素数,因为1除以每个数字,

while (runs < found) //has number passed all tests
{
    if (number % prime[runs] !== 0) //is number divisible by smaller prime
    {
        runs = runs + 1; //number passed a test
    }
    else //number failed a test
    {
        number = number + 1; //next number generated
        runs = 0; //reset test counter for next number
        setTimeout(test, 1000); //start running next number tests
    }
} //number passed all tests

总是进入else分支runs = 0

您可以从var prime = [2];var prime = [];和开始var found = 0;

于 2013-05-08T17:03:47.077 回答