[尝试编写一个接受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);
• 以非阻塞方式将数据从事件线程传递到持续运行的线程的最高效/优雅/稳健的解决方案 (C++20)
• 如何让这个计算器应用程序为两种不同的方法制作两个不同的场景
• 尝试在大型数组中找到最大的第 k 个元素时出现 OutOfMemoryError
• javax.security.auth.login.LoginException:将应用程序迁移到 Java 11 时未找到 LoginModule
• 使用 Google Nest Hub 2nd 进行物质测试
• jruby java.sql.DriverManager 有问题吗?找不到适合 jdbc 的驱动程序:mysql://localhost/mydatabase
• ArrayIndexOutOfBoundsException 寻找最大公约数的方法中的错误
• ClarifaiChannel.INSTANCE.getGrpcChannel() 抛出 IllegalStateException:找不到 TLS ALPN 提供商
• MySQL - 为每年每个月的最佳客户查找计费和非计费时间