我的代码有什么错误?计算 n 以内的素数
What is the mistake in my code? Computing prime numbers upto n
function primesuntil(n) {
var primes = [2];
for (i=3; i < n ; i++) {
var j=0;
while (j<primes.length) {
var quotient = i/primes[j];
if (quotient !== math.floor(quotient) {
var hasDivisor = false;
j++;
}
else {
var hasDivisor = true;
j=primes.length+15;
}
}
if (hasDivisor == false)
{primes.push(i);}
else
{var nothing = 3;}
}
printarray(primes);
}
我想 运行 JavaScript 中的这段代码,它应该打印所有小于 n 的素数,但由于某些原因它不会 运行。我在某处犯了错误吗?当我将此函数注释掉时,其余代码确实 运行。
代码应该做的是将数组 "primes" 中的所有数字相除,如果在某个时候商等于该数字的 'floor' (意味着它可以被数组中的数字整除),则 hasdivisor 变为true 并且数字不会添加到素数数组中。此外,j 停止计数(我们不必再除以其他素数,我们知道它不是素数)。如果它不除任何比自己小的素数,它就是素数,所以它被添加到列表中。怎么了?
您在这一行中缺少右括号:
if (quotient !== math.floor(quotient)) {
是if (quotient !== math.floor(quotient))
一个额外的)
,也是Math.floor
,大写M
。
function primesuntil(n) {
var primes = [2];
for (i=3; i < n ; i++) {
var j=0;
while (j<primes.length) {
var quotient = i/primes[j];
if (quotient !== math.floor(quotient) {
var hasDivisor = false;
j++;
}
else {
var hasDivisor = true;
j=primes.length+15;
}
}
if (hasDivisor == false)
{primes.push(i);}
else
{var nothing = 3;}
}
printarray(primes);
}
我想 运行 JavaScript 中的这段代码,它应该打印所有小于 n 的素数,但由于某些原因它不会 运行。我在某处犯了错误吗?当我将此函数注释掉时,其余代码确实 运行。 代码应该做的是将数组 "primes" 中的所有数字相除,如果在某个时候商等于该数字的 'floor' (意味着它可以被数组中的数字整除),则 hasdivisor 变为true 并且数字不会添加到素数数组中。此外,j 停止计数(我们不必再除以其他素数,我们知道它不是素数)。如果它不除任何比自己小的素数,它就是素数,所以它被添加到列表中。怎么了?
您在这一行中缺少右括号:
if (quotient !== math.floor(quotient)) {
是if (quotient !== math.floor(quotient))
一个额外的)
,也是Math.floor
,大写M
。