Created
May 8, 2020 14:33
-
-
Save theraccoonbear/a8179581416103b9e1f8c27aeee4837d 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 argv = require('yargs').argv; | |
let sieve = {}; | |
let timeAtStart; | |
// like a boss | |
Object.prototype.commafy = function () { | |
return this.toString().replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) { | |
return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,"); | |
}); | |
} | |
const startTimer = (title = "Timer:") => { | |
console.log(title); | |
timeAtStart = (new Date()).getTime(); | |
} | |
const stopTimer = () => { | |
const delta = (new Date()).getTime() - timeAtStart; | |
timeAtStart = null; | |
console.log(`${(delta / 1000).toFixed(2)} second(s) elapsed`) | |
console.log('-----------------------------------------------------------------'); | |
return delta; | |
} | |
const isPrime = (n, useSieve = false) => { | |
const numToCheck = parseInt(n); | |
if (numToCheck <= 1) { | |
return false; | |
} | |
if (useSieve && typeof sieve[numToCheck] !== 'undefined') { | |
return sieve[numToCheck]; | |
} | |
const top = Math.floor(Math.sqrt(numToCheck)); | |
const prime = [...new Array(top)] // make an array of size top | |
.map((v, idx) => idx + 2) // make the array 2..(top + 2) | |
.reverse() // reverse | |
.reduce((prev, cur) => !!(prev & (numToCheck % cur != 0)), true); // use a reducer to determine primacy | |
if (useSieve) { // if we're using the sieve, populate it | |
sieve[numToCheck] = prime; | |
let mult = numToCheck + numToCheck; | |
while (mult < sieveMax) { | |
sieve[mult] = false; // all multiples of numToCheck are non-prime | |
mult += numToCheck; | |
} | |
} | |
return prime; | |
} | |
const checkRange = argv.check || 1000000; | |
const sieveMax = Math.min(checkRange, argv.sieveMax || 10000000); | |
let primeCount = 0; | |
startTimer(`Primes between 1 and ${checkRange.commafy()} WITH sieve:`); | |
for (x of [...new Array(checkRange)].map((x, i) => i + 1)) { | |
if (isPrime(x, true)) { | |
primeCount++; | |
} | |
} | |
console.log(` ${primeCount.commafy()} primes!`); | |
stopTimer(); | |
primeCount = 0; | |
startTimer(`Counting primes between 1 and ${checkRange.commafy()} WITHOUT sieve:`); | |
for (x of [...new Array(checkRange)].map((x, i) => i + 1)) { | |
if (isPrime(x, false)) { | |
primeCount++; | |
} | |
} | |
console.log(` ${primeCount.commafy()} primes!`); | |
stopTimer(); | |
sieve = {}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment