Skip to content

Instantly share code, notes, and snippets.

@alex-cory
Last active July 30, 2017 22:54
Show Gist options
  • Save alex-cory/d756ddd13fd69fd5e8fe5499e5df1f53 to your computer and use it in GitHub Desktop.
Save alex-cory/d756ddd13fd69fd5e8fe5499e5df1f53 to your computer and use it in GitHub Desktop.
JS isPrime
/**
* 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