Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created February 9, 2017 17:33
Show Gist options
  • Save jasonwaters/91fb0d9ac2fc2f350da83b0f9e9a47e1 to your computer and use it in GitHub Desktop.
Save jasonwaters/91fb0d9ac2fc2f350da83b0f9e9a47e1 to your computer and use it in GitHub Desktop.
is prime?
// A prime number is a natural number that has exactly two distinct natural number divisors: 1 and itself.
const isPrime = (function () {
let primes = {};
let notPrimes = {};
return function (number) {
if(primes[number]) return true;
if(number === 1 || notPrimes[number]) return false;
for (let i = 2; i <= parseInt(Math.sqrt(number)); i++) {
if (number % i === 0) {
notPrimes[number] = true;
return false;
}
}
primes[number] = true;
return true;
}
})();
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 907].forEach(value => console.log(isPrime(value)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment