Skip to content

Instantly share code, notes, and snippets.

@crates
Created December 7, 2022 21:07
Show Gist options
  • Save crates/3b47122b482eb4e02e39870398829052 to your computer and use it in GitHub Desktop.
Save crates/3b47122b482eb4e02e39870398829052 to your computer and use it in GitHub Desktop.
Check to see if a number is prime (generated with some help from ChatGPT)
// Create an object to store the results of previous calculations
const primeCache = {
2: true,
3: true,
5: true,
7: true,
11: true,
13: true,
17: true,
19: true,
23: true,
29: true,
31: true,
37: true,
41: true,
43: true,
47: true,
53: true,
59: true,
61: true,
67: true,
71: true,
73: true,
79: true,
83: true,
89: true,
97: true,
};
const hasNonPrimeRemainder = (num) => {
const remainders = [2, 4, 5, 6, 8, 0];
if (remainders.includes(num % 10)) {
return true;
}
return false;
};
const isNotAnInteger = (num) => {
return num % 1 !== 0;
}
function isPrime(num) {
// Check if the result of the calculation has been memoized
if (primeCache[num]) {
return primeCache[num];
}
if (isNotAnInteger(num) ||
num < 2 ||
hasNonPrimeRemainder(num) ||
num % 2 === 0 ||
num % 3 === 0 ||
num % 5 === 0
) {
primeCache[num] = false;
return false;
}
// Check if the number is divisible by any other number up to the square root of the number
let i = 5;
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) {
primeCache[num] = false;
return false;
}
i += 6;
}
// If the number passes all tests, it is a prime number
primeCache[num] = true;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment