Last active
July 30, 2017 22:54
-
-
Save alex-cory/d756ddd13fd69fd5e8fe5499e5df1f53 to your computer and use it in GitHub Desktop.
JS isPrime
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
/** | |
* by definition, primes cannot be negative | |
*/ | |
const isPrime = value => { | |
for(var i = 2; i < value; i++) { | |
if(value % i === 0) { | |
return false; | |
} | |
} | |
return value > 1; | |
} | |
var isPrime = n => n > 1 && Array.from({ length: Math.floor(Math.sqrt(n)) - 1 },(_,i) => i + 2).every(m => n % m); | |
// or | |
var isPrime = n => n>1 && !/^(oo+)\1+$/.test('o'.repeat(n)) // inefficient for big numbers | |
// test - generate list of all primes 1 - 101 | |
Array.from({length:101}, (_,i)=>i).filter(isPrime) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment