素数测试问题javascript

时间:2016-06-21 17:51:41

标签: javascript for-loop

我是初学者并尝试完成素数测试,但我遇到了一个问题。这就是我所拥有的:

var n = Number(prompt("Input the number you want to check for prime:"));
var i;


if (n < 2) {
    alert(n + " is not a prime number.");
}
for (var i = 2; i <= Math.sqrt(n); i++) {
    if (n % i === 0) {
        alert(n + " is not a prime number.");
        break;
    }

    else {
        alert(n + " is a prime number."); 
        break;
    }
}

它正常运行,但是如果我输入3或2则不会弹出警报,并且任何带有3的数字即使不是素数也会返回作为素数。除此之外,我的所有测试都有效。

3 个答案:

答案 0 :(得分:1)

啊,你的问题是你构建循环的方式。无论支票是否完成,您都会爆发。

var n = Number(prompt("Input the number you want to check for prime:"));
var i;
var isPrime = true;

if (n < 2) {
    isPrime = false;
} else if (n < 4 && n >= 2) {
    // isPrime is already true
} else if (n % 2 === 0) {
    isPrime = false; // no divisor of 2 can be prime
} else {
  var sqrtN = Math.sqrt(n);
  for (var i = 3; i <= sqrtN; i = i + 2) {
      if (n % i === 0) {
          // Only break out of the loop if a match is found
          isPrime = false;
          break;
      }
  }
}
if (isPrime) {
    alert(n + " is a prime number.");
} else {
    alert(n + " is not a prime number.");
}

或者,或许更有组织的解决方案:

function isPrime (n) {
  n = parseInt(n);
  var i;
  if (Number.isNaN(n)) {
    return false;
  } else if (n < 2) {
    // 1 is not prime
    return false;
  } if (n < 4) {
    // 2 and 3 are prime, so why not skip checking them?
    return true;
  } else if (n % 2 === 0) {
    // No number divisible by 2 is prime.
    return false;
  } else {
    // This won't change, so calculate it once as suggested by Weather Vane.
    var sqrtN = Math.sqrt(n);
    // 4, 6, 8... All divisible by 2, and would be caught by initial check.
    for (i = 3; i < sqrtN; i = i + 2) { 
      // Not a prime if it's evenly divisible. 
      if (n % i === 0) {
        return false; 
      }
   }
   // Otherwise prime.
   return true; 
  }
}

答案 1 :(得分:1)

当然。如果n % i不是0,则表示i不会划分n,但这并不意味着n是素数。您必须检查所有i才能说出来。

此外,不要在每次迭代时重新计算昂贵的Math.sqrt(n)。并注意NaN

&#13;
&#13;
var n = Number(prompt("Input the number you want to check for prime:"));
function isPrime(n) {
  if (n < 2 || !n) return false;
  for (var i = 2; i*i <= n; i++) {
    if (n % i === 0) return false;
  }
  return true;
}
alert(n + " is " + (isPrime(n) ? "" : "NOT ") + "a prime number.");
&#13;
&#13;
&#13;

当然,这个算法是指数式的(pseudo-polynomial)。不要将它用于大n。相反,请参阅例如Miller–Rabin primality testAKS primality test,它们是多项式的。

答案 2 :(得分:0)


<div *ngIf="conferenceData">
    <div *ngFor="#session of conferenceData.sessions">
        {{session.title}}
    </div>
</div>

请参考stackoverflow中提出的旧问题 link to the old question