Skip to content

Instantly share code, notes, and snippets.

@shai-almog
Created October 19, 2021 11:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shai-almog/167a34571b0fae6eeed56742c44895cd to your computer and use it in GitHub Desktop.
Save shai-almog/167a34571b0fae6eeed56742c44895cd to your computer and use it in GitHub Desktop.
Prime number calculator used as part of a debugging tutorial on talktotheduck.dev
const MAX_NUMBER = 10 ** 9;
let cnt = 0
function isPrime(num) {
if (num === 2) {
return true;
}
if (num < 2 || num % 2 === 0) {
return false;
}
for (let i = 3; i * i <= num; i += 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
function countPrimes(i) {
if (isPrime(i)) {
cnt++;
}
if (i < MAX_NUMBER) {
setTimeout(() => countPrimes(++i));
} else {
console.log("Total number of primes: " + cnt);
}
}
console.log("Starting to count prime numbers...");
setTimeout(() => countPrimes(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment