[尝试编写一个接受2个正整数并返回它们之间的最高质数的javascript函数,否则,返回适当的错误消息。如果输入数字是50和75,则输出应该是73;如果输入数字是-50,-75,则输出应该是错误消息。
但是我不确定为什么我的代码返回最大的奇数。
这是我的代码:
function highestPrimeInRange(int1, int2) {
if (int1 <= 0 || int2 <= 0) {
alert("Both numbers should be positive and non 0");
}
let highestPrime;
for (let i = int1; i <= int2; i++) {
let primeFlag = true;
for (let j = 2; j <= i / 2; j++) {
if (i % j == 0) {
primeFlag = false;
break;
}
if (primeFlag) {
highestPrime = i;
}
}
}
alert(highestPrime);
}
highestPrimeInRange(50, 75);
有人可以帮我解决我要去的地方吗?
更新highestPrime
的代码应在j
循环之外。当输入超出范围时,您还需要从函数中返回,而不是继续使用查找代码。
function highestPrimeInRange(int1, int2) {
if (int1 <= 0 || int2 <= 0) {
alert("Both numbers should be positive and non 0");
return;
}
if (int1 >= int2) {
alert("First number should be less than second");
return;
}
let highestPrime;
for (let i = int1; i <= int2; i++) {
let primeFlag = true;
for (let j = 2; j <= i / 2; j++) {
if (i % j == 0) {
primeFlag = false;
break;
}
}
if (primeFlag) {
highestPrime = i;
}
}
alert(highestPrime);
}
highestPrimeInRange(50, 75);
highestPrimeInRange(-50, -75);
highestPrimeInRange(10, 100);
但是最好从最高的数字开始循环,并在获得第一个素数时停止。
function highestPrimeInRange(int1, int2) {
if (int1 <= 0 || int2 <= 0) {
alert("Both numbers should be positive and non 0");
return;
}
if (int1 >= int2) {
alert("First number should be less than second");
return;
}
for (let i = int2; i >= int1; i--) {
let primeFlag = true;
for (let j = 2; j <= i / 2; j++) {
if (i % j == 0) {
primeFlag = false;
break;
}
}
if (primeFlag) {
alert(i);
break;
}
}
}
highestPrimeInRange(50, 75);
highestPrimeInRange(-50, -75);
highestPrimeInRange(10, 100);