我正在研究质数算法,并且几乎完成了它。.我认为输出数组在每次循环结束时都会更新,因此如果我用质数调用函数:例如primes(7)
,则得到[7]
而不是[2,3,5,7]
。如果使用非质数调用,则输出arr为空。
这是代码:
function rimes(num){
var outputArr = [];
for(var i=1; i<=num; i++){
function range(start, count) {
return Array.apply(0, Array(count))
.map(function (element, index) {
return index + start;
});
}
var rangeArr = range(1,num);
var current = i;
function rangeFiltering(value){
return value !== 1 && value < current;
}
var filteredRange = rangeArr.filter(rangeFiltering);
function dividingByEachRangeElement(rangeElement){
return current % rangeElement !== 0;
}
var divided = filteredRange.filter(dividingByEachRangeElement);
if(divided.length === num - 2){ //current is prime if there are all numbers from 1 to current in divided array.(if there are zeros after modulo) i.e. when current is 5(prime), divided array is [2,3,4]. When current is 6(non prime), divided arr is [4,5] - 2,3 are missing because 6%2 = 0 and 6%3 = 0.
outputArr.push(current);
}
}
console.log(outputArr);
}
sumPrimes(47);
//sumPrimes(6) -> [];
//sumPrimes(7) -> [7];
//sumPrimes(11) -> [11];
我怎样才能解决这个问题?
最佳答案
您的问题就在网上:if(divided.length === num - 2)
这意味着仅当outputArr
的长度恰好等于divided
时,当前数字才添加到num - 2
,在本例中,仅当i
或current
等于7
时才是正确的。
更改为:if(divided.length === current - 2)
应该可以。