Skip to content

Commit 845d1a0

Browse files
authored
Create 010.js
1 parent 93174a1 commit 845d1a0

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

010.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Source: https://projecteuler.net/problem=10
3+
4+
Problem:
5+
"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+
function sieveOfEratosthenes(n) {
17+
let numbersUntilN = []
18+
let upperLimit = Math.sqrt(n);
19+
let primesUntilN = [];
20+
21+
for (let i = 0; i < n; i++) {
22+
numbersUntilN.push(true); //makes an array from 2 to n-1
23+
}
24+
25+
for (let i = 2; i <= upperLimit; i++) {
26+
if (numbersUntilN[i]) {
27+
for (let j = 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 (let i = 2; i < n; i++) {
36+
if(numbersUntilN[i]) {
37+
primesUntilN.push(i);
38+
}
39+
}
40+
41+
return primesUntilN;
42+
}
43+
44+
function solution(n) {
45+
let primesUntilN = sieveOfEratosthenes(n);
46+
47+
const add = (a, b) => a + b;
48+
return primesUntilN.reduce(add);
49+
}
50+
51+
console.log(solution(2000000)); //outputs the answer!

0 commit comments

Comments
 (0)