The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
function sumPrimes(num:number):number {
let sum = 0;
const sieve = [];
const primes = [];
// create a sieve of size num
for (let i = 0; i < num; i++) {
sieve[i] = true;
}
// mark all multiples of primes as non-primes
for (let i = 2; i < num; i++) {
if (sieve[i]) {
for (let j = i * i; j < num; j += i) {
sieve[j] = false;
}
}
}
// get all primes
for (let i = 2; i < num; i++) {
if (sieve[i]) {
primes.push(i);
}
}
// add all primes to sum
for (let i = 0; i < primes.length; i++) {
sum += primes[i];
}
return sum;
}
Thoughts:
this is the second iteration of this solution, as the first was doing the simple number crawling I complained about earlier, but took 10 minutes +