该程序的目的是列出从 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>