Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active February 20, 2019 03:21
Show Gist options
  • Save lewdev/3cc699e7f498455e5c6364407efbcaf1 to your computer and use it in GitHub Desktop.
Save lewdev/3cc699e7f498455e5c6364407efbcaf1 to your computer and use it in GitHub Desktop.
JavaScript Prime Number test
function isPrime(num) {
//check if value is a natural numbers (integer)
//without this check, it returns true
if (isNaN(num) || num % 1 !== 0) {
return false;
}
num = Math.abs(num); //*negative values can be primes
if (num === 0 || num === 1) {
return false;
}
const maxFactorNum = Math.sqrt(num);
for (let i = 2; i <= maxFactorNum; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment