Last active
January 17, 2018 21:06
-
-
Save geraldfullam/164ce3268ebc896c0cf06e82220da409 to your computer and use it in GitHub Desktop.
Extends the Math object with isPrime, optimized to check only odd numbers greater than two and less than square root.
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
Math.isPrime = function (n) { | |
if (n === 2) { return true; } | |
if (n % 2 === 0) { return false; } | |
for(let i = 3, s = Math.sqrt(n); i <= s; i += 2) { | |
if (n % i === 0) { return false; } | |
} | |
return n !== 1; | |
}; | |
// Based on this StackOverflow answer: https://stackoverflow.com/a/40200710/2502532 | |
// JSPerf test to demonstrate optimization: https://jsperf.com/math-isprime/1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My ReasonML experimentation this morning at the coffee shop: