Created
September 2, 2015 13:33
-
-
Save tjeastmond/7dfd6d43b9bac6e599fc to your computer and use it in GitHub Desktop.
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
var isInteger = function(x) { return (x ^ 0) === x; }; | |
function isPrime(number) { | |
if (typeof number !== 'number' || !isInteger(number)) { | |
// Alternatively you can throw an error. | |
return false; | |
} | |
if (number < 2) { | |
return false; | |
} | |
if (number === 2) { | |
return true; | |
} else if (number % 2 === 0) { | |
return false; | |
} | |
var squareRoot = Math.sqrt(number); | |
for(var i = 3; i <= squareRoot; i += 2) { | |
if (number % i === 0) { | |
return false; | |
} | |
} | |
return true; | |
} | |
console.log('isPrime(5):', isPrime(5)); | |
console.log('isPrime("10"):', isPrime("10")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment