用JS检查是否是素数
我首先尝试仅将素数(不含 2)推入数组,然后将它们全部求和,但未定义。
我已经为此工作了很长时间,如果有人能帮助我,我将不胜感激。
let letsCheck = () => {
let ourList = []
let sum = 0
for(let i = 2; i <= 50; i++) {
if(i % 2 !== Number.isInteger()) {
ourList.push(Number(i))
}
}
for(let prime in ourList) {
sum += ourList[prime]
}
}
I'm first trying to push only prime numbers (without 2) to an array and then sum them all but getting undefined.
I've been working on this for long days, I'd appreciate if anyone could help me.
let letsCheck = () => {
let ourList = []
let sum = 0
for(let i = 2; i <= 50; i++) {
if(i % 2 !== Number.isInteger()) {
ourList.push(Number(i))
}
}
for(let prime in ourList) {
sum += ourList[prime]
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您不是在检查素数,而是通过 % 运算符检查奇数。
其次,您正在检查 Number.isNumber 函数,该函数将返回布尔值,因此比较存在一些问题。
这是一种可能有帮助的解决方案。
First of all, You are not checking prime but checking odd numbers by % operator.
Second, you are checking Number.isNumber function which will return the boolean so, the comparison have some issues.
Here is one solution which may help.
从您的代码中,更有可能获得奇数/偶数而不是质数。
然后,作为基本的编程数学,mod 的工作方式类似于乘法/加法/减法如果两个运算符/数字都是
整数
,则结果将为整数
。 mod 运算基本上是为了获得除法的余数,即5 / 2 = 2,余数 = 1
,因此5 % 2 = 1
代码>.并且,在循环中,
i
已经是一个数字,因此推送Number(i)
相当于单独推送i
。如果您只想获得总和,则不需要该数组,只需将其删除即可。您可以通过将其累加到sum
变量中来获得总和。因此,如果您希望获得[2,50]范围内的奇数之和,则应该是:
如果你想得到 0 到 50 之间除 2 之外的质数,应该是:
From, your code, it was more likely for obtaining odd/even numbers instead of prime numbers.
Then, as the basic programming math, the mod works like multiplication/add/subtraction that if both operators/numbers are
Integer
, the result would beInteger
. The mod operation is basically for obtaining the remainders from the division, i.e.5 / 2 = 2, with remainders = 1
, thus5 % 2 = 1
.And, in the looping, the
i
is already a number, so pushing theNumber(i)
is equivalent with pushingi
alone. If you just want to get the sum, the array is not necessary there and should be just removed. You can get the sum by accumulate it into thesum
variable.Thus, if you wish to get the sum of odd numbers in the range [2,50], it should be:
And if you wish to get the prime numbers from 0 to 50 excluding 2, it should be: