Last active
August 29, 2015 14:20
-
-
Save sscovil/6997e2eed8c02ee7cf21 to your computer and use it in GitHub Desktop.
JavaScript algorithms, math functions, etc.
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(n) { | |
// Eliminate any non-numeric values | |
if (typeof(n) === 'boolean' || n === null || isNaN(n)) | |
return false; | |
// Handle first two prime numbers | |
if (n === 2 || n === 3) | |
return true; | |
// Handle numbers that are definitely not prime | |
if (n < 3 || n % 1 !== 0 || n % 2 === 0) | |
return false; | |
// Check if n divides evenly by any odd number between 3 and it's square root (inclusive) | |
var divisor = 3; | |
while (divisor <= Math.sqrt(n)) { | |
if (n % divisor === 0) return false; | |
else divisor += 2; | |
} | |
// We can safely say that n is only evenly divisible by itself and 1, thus it is prime | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment