Skip to content

Instantly share code, notes, and snippets.

@kwyn
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwyn/11325008 to your computer and use it in GitHub Desktop.
Save kwyn/11325008 to your computer and use it in GitHub Desktop.
/**
* A prime number is a whole number that has no other divisors other than
* itself and 1. Write a function that accepts a number and returns true if it's
* a prime number, false if it's not.
*/
var primeTester = function(n) {
if( n === 1) return false;
var limit = Math.ceil(Math.sqrt(n));
for(var i = limit; i > 1; i--){
if(n%i === 0) return false;
}
return true
};
/* Extra credit: Write a function that generates a list of all prime numbers
* in a user-specified range (inclusive). If you're not quite sure where to start,
* check out the Sieve of Eratosthenes on Wikipedia. (And if you're feeling
* saucy, check out the Sieve of Atkin.)
*/
var primeSieve = function(start, end) {
// Return a list of all prime numbers >= start and <= end
var primes = [];
var markers = Array(end); //inclusive
for(var i =2; i < end; i++){
if(markers[i]===undefined){
if(i >= start) primes.push(i);
for(var j = i*i; j < markers.length; j+=i){
markers[j] = "Not prime";
}
}
}
return primes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment