Last active
February 20, 2019 03:21
-
-
Save lewdev/3cc699e7f498455e5c6364407efbcaf1 to your computer and use it in GitHub Desktop.
JavaScript Prime Number test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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