JavaScript Prime编号查询
这是我的代码:
var num = parseInt(105);
// debugger
if (num < 1) {
console.log("=> 0 or minus value is not a prime number", num);
} else if (num == 2) {
console.log("=> 2 is a prime number", num);
} else if (num > 2) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
console.log("this is a not prime number as it is devided by zero");
break
} else {
console.log("this is a prime number")
}
}
}
在此代码中,为什么当我将任何奇数数字放置在我已经磨损的任何奇数时,请显示输出,以停止循环中断。
this is my code :
var num = parseInt(105);
// debugger
if (num < 1) {
console.log("=> 0 or minus value is not a prime number", num);
} else if (num == 2) {
console.log("=> 2 is a prime number", num);
} else if (num > 2) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
console.log("this is a not prime number as it is devided by zero");
break
} else {
console.log("this is a prime number")
}
}
}
in this code why else statement is showing the output when I put any odd numbers where I already worte the break statement for stopping the loop break.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果该数字不能由特定的
i
排除,那么您的其他条件将被执行。更改num
为5
您会看到这是一个素数
打印几次。您可以创建一个函数(如下所示),在其中我们首先检查所有
i
s,然后打印这是一个Prime Number
。或者,您可以将结果存储在变量中,并且在循环打印
的末尾,如果未设置该变量,则是素数
。If the number is not divisible by a particular
i
then your else condition is being executed. Changenum
to5
you would seethis is a prime number
print several times.You can create a function (as shown below) where we first check all the
i
s then printthis is a prime number
.Or you can store the result in a variable, and at the end of the loop print
this is a prime number
if the variable wasn't set.