You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
"The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
6
+
7
+
Find the sum of all the primes below two million."
8
+
9
+
10
+
My Algorithm:
11
+
1. Use the Sieve of Eratosthenes method to generate prime numbers
12
+
The algorithm in a gif: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
13
+
2. Execute a reducer function to add up all the numbers in the array of prime numbers
14
+
*/
15
+
16
+
functionsieveOfEratosthenes(n){
17
+
letnumbersUntilN=[]
18
+
letupperLimit=Math.sqrt(n);
19
+
letprimesUntilN=[];
20
+
21
+
for(leti=0;i<n;i++){
22
+
numbersUntilN.push(true);//makes an array from 2 to n-1
23
+
}
24
+
25
+
for(leti=2;i<=upperLimit;i++){
26
+
if(numbersUntilN[i]){
27
+
for(letj=i*i;j<n;j+=i){
28
+
numbersUntilN[j]=false;//"cross out" the numbers that are multiples of i, like in the algorithm gif https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
29
+
}
30
+
}
31
+
}
32
+
33
+
34
+
//after the "crossing-out" is done, push the ones that are left to the primesUntilN array
35
+
for(leti=2;i<n;i++){
36
+
if(numbersUntilN[i]){
37
+
primesUntilN.push(i);
38
+
}
39
+
}
40
+
41
+
returnprimesUntilN;
42
+
}
43
+
44
+
functionsolution(n){
45
+
letprimesUntilN=sieveOfEratosthenes(n);
46
+
47
+
constadd=(a,b)=>a+b;
48
+
returnprimesUntilN.reduce(add);
49
+
}
50
+
51
+
console.log(solution(2000000));//outputs the answer!
0 commit comments