为什么我的JavaScript Prime Number-Generator不起作用?

时间:2013-05-08 15:48:08

标签: javascript math web-applications primes

该计划的目的是列出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>

2 个答案:

答案 0 :(得分:0)

有几点需要注意:

  1. for (runs < found)

    您似乎想要while loopfor循环不能只包含条件。

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

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

    var line = document.createElement('div');
    line.innerHTML = number;
    document.body.appendChild(line);
    
  4. 为了避免无限递归并为UI线程提供更新页面显示的机会,您可以在再次致电testuse a timer

    setTimeout(test, 100);
    

答案 1 :(得分: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的{​​{1}}分支。

您可以从runs = 0var prime = [2];var prime = [];开始。