简体   繁体   English

获取前 N 个素数的总和 javascript

[英]Get the sum of first N primes javascript

I am trying to find the sum of the first N primes, below I have attached my code.我试图找到前 N 个素数的总和,下面我附上了我的代码。 I am struggling with the last part (getting the sum).我正在为最后一部分苦苦挣扎(求和)。 So far I have defined what a prime number is and got the first N prime numbers到目前为止,我已经定义了素数并得到了前 N 个素数

 function isPrime(number) { if (number <= 1) return false; if (number === 2) return true; else { for (let i = 2; i < number; i++) { if (number % i === 0) return false; } return true; } } console.log(isPrime(6)); //false function getNprimes(n) { const arr = []; let i = 2 while (arr.length < n) { if (isPrime(i)) { arr.push(i) } i++ } return arr; } console.log(getNprimes(5)); //[2, 3, 5, 7, 11] const sumOfNPrimes = (num) => { let sum = getNprimes(num); if (sum === 0) { sum = getNprimes(num + 1) return sum; } } console.log(sumOfNPrimes(4));

The check sum === 0 will always return false since sum is an array and you are using strict equality, which checks for types. check sum === 0将始终返回false因为sum是一个数组,并且您使用的是严格相等,它检查类型。 You should be checking the length property instead, and using the != operator (eg, only execute the code if the length of the array is not 0 ).您应该改为检查length属性,并使用!=运算符(例如,仅当数组的长度不为0时才执行代码)。

To calculate the sum of the resulting array, you can use Array#reduce :要计算结果数组的总和,您可以使用Array#reduce

 function isPrime(number) { if (number <= 1) return false; if (number === 2) return true; else { for (let i = 2; i < number; i++) { if (number % i === 0) return false; } return true; } } console.log(isPrime(6)); //false function getNprimes(n) { const arr = []; let i = 2 while (arr.length < n) { if (isPrime(i)) { arr.push(i) } i++ } return arr; } console.log(getNprimes(5)); //[2, 3, 5, 7, 11] const sumOfNPrimes = (num) => { let sum = getNprimes(num).reduce((a, b) => a + b); return sum } console.log(sumOfNPrimes(4));

The algorithm you have implemented will run in O(N sqrt(N)) and it is finding the sum for every query.您实现的算法将在 O(N sqrt(N)) 中运行,并且它正在为每个查询找到总和。 So, if you want to reduce the time complexity of your code then you can implement sieve of erastosthenes which runs in O(N log (log N)) and store the values of sums of prime numbers in O(N) and then answer all queries in O(1) time complexity.因此,如果您想降低代码的时间复杂度,那么您可以实现以 O(N log (log N)) 运行的橡皮擦筛,并将质数之和的值存储在 O(N) 中,然后回答所有O(1) 时间复杂度的查询。 Below is the implementation of this idea in javascript:下面是这个想法在 javascript 中的实现:

let primes = [];
let primeSum = [2];
const N = 1000001;

function generatePrimes(){
    let isPrime = [];
    for(let i=1; i<N; i++) isPrime.push(true);
    for(let i=2; i<N; i++){
        if(!isPrime[i]) continue; // if number is not prime
        primes.push(i); // add prime number
        for(let j=2*i; j<N; j += i){
            isPrime[j] = false; // marking all multiples of                  current prime as non prime
        }
    }

// calculate prime sums from 0 index to ith index
    for(let i=1; i<primes.length; i++){
        if(i < 10) console.log(primes[i]);
        primeSum.push(Number(Number(primes[i])+Number(primeSum[i-    1])));
    }
}

generatePrimes();

// answer query in O(1) for n = 10:
const n = 3;
console.log(primeSum[n-1]);

you can also answer l to r range query prime sums with this code您还可以使用此代码回答 l 到 r 范围查询质数

ps: sorry for bad english ps:抱歉英语不好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM