Created
October 7, 2014 05:49
-
-
Save jonalvarezz/a46eed08b2eb4d9a092a to your computer and use it in GitHub Desktop.
Prime numbers algorithm in Javascript
This file contains hidden or 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(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