Created
August 30, 2018 03:56
-
-
Save adityathebe/2a3b56702c00d5d6b6e2f2d51c616492 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const eratosthenes = (n) => { | |
// Eratosthenes algorithm to find all primes under n | |
let array = [] | |
let output = []; | |
let upperLimit = Math.sqrt(n) | |
// Make an array from 2 to (n - 1) | |
for (var i = 0; i < n; i++) { | |
array.push(true); | |
} | |
// Remove multiples of primes starting from 2, 3, 5,... | |
for (var i = 2; i <= upperLimit; i++) { | |
if (array[i]) { | |
for (var j = i * i; j < n; j += i) { | |
array[j] = false; | |
} | |
} | |
} | |
// All array[i] set to true are primes | |
sum = 0; | |
for (var i = 2; i < n; i++) { | |
if(array[i]) { | |
sum += i; | |
} | |
} | |
return sum; | |
}; | |
console.time('main') | |
let result = eratosthenes(1000000); | |
console.timeEnd('main') | |
console.log(result) | |
// fs.appendFileSync('data.txt', result + '\n', 'utf8') | |
// console.log(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment