Skip to content

Instantly share code, notes, and snippets.

@jonalvarezz
Created October 7, 2014 05:49
Show Gist options
  • Save jonalvarezz/a46eed08b2eb4d9a092a to your computer and use it in GitHub Desktop.
Save jonalvarezz/a46eed08b2eb4d9a092a to your computer and use it in GitHub Desktop.
Prime numbers algorithm in Javascript
function isPrime(number) {
// If your browser doesn't support the method Number.isInteger of ECMAScript 6,
// you can implement your own pretty easily
if (typeof number !== '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;
}
// don’t need to test numbers greater than the square root of the input number
var squareRoot = Math.sqrt(number);
for(var i = 3; i <= squareRoot; i += 2) {
if (number % i === 0) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment