Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Last active July 29, 2020 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitalconceptvisuals/d993ade0108037564b280c78edb762c6 to your computer and use it in GitHub Desktop.
Save digitalconceptvisuals/d993ade0108037564b280c78edb762c6 to your computer and use it in GitHub Desktop.
// We store previous results here
const cache = {};
// Check if given number is prime
const isPrime = number => {
// Check cache if we have previous result
if (number in cache) {
console.log(`Found ${number} in cache: ${cache[number]}`);
return cache[number];
}
if (number < 2) return false;
// Divide number by all numbers from 2 to sqrt(number)
// If divisible, then its not a prime
let div;
for (div = 2; div < Math.sqrt(number); div++)
if (number % div == 0) {
console.log(`Looped ${div} times`);
cache[number] = false;
return false;
}
console.log(`Looped ${div} times`);
cache[number] = true;
return true;
}
// This is a known prime
let number = 1299827;
console.log(`${number} is prime: ${isPrime(number)}`);
console.log(`${number} is prime: ${isPrime(number)}`);
/* Output
Looped 1141 times
1299827 is prime: true
Found 1299827 in cache: true
1299827 is prime: true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment