gpt4 book ai didi

javascript - 质数测试 javascript 的问题

转载 作者:行者123 更新时间:2023-12-02 14:29:32 25 4
gpt4 key购买 nike

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

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 的数字都会作为素数返回,即使它不是素数。除此之外,我的所有测试都有效。

最佳答案

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

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;
}
}

关于javascript - 质数测试 javascript 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com