Skip to content

Instantly share code, notes, and snippets.

@tjeastmond
Created September 2, 2015 13:33
Show Gist options
  • Save tjeastmond/7dfd6d43b9bac6e599fc to your computer and use it in GitHub Desktop.
Save tjeastmond/7dfd6d43b9bac6e599fc to your computer and use it in GitHub Desktop.
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