Post: JavaScript: Finding primes

In the spirit of one of my previous posts, I’m releasing a new JavaScript library extracted out of code I wrote for Project Euler. This time, it’s a library to find primes and to check numbers for their primality.

It’s a simple library, based on the Sieve of Eratosthenes, which uses on the fact that non-primes are always divisible by a prime less than or equal to their square root to efficiently calculate whether a number is a prime or not. There also exists a Sieve of Atkin, a faster but more complex algorithm. I didn’t use that one, preferring code readability over performance.

The library contains two functions: Primes.at(n) to find the prime at position n in the prime sequence (starting at 0), and Primes.is_prime(int) to check whether int is a prime. There’s also one variable, Primes.primes, containing all primes found so far, but normally you shouldn’t need to access that one.

You can download the script here (1.8 kB), and I also made an example. Report any bugs in the comments.

Update: A new version of this script was released, greatly improving performance. Calculating large primes is now about 50% faster, calculating the first 100 primes up to 20%. You can download the new script using the same link above, the old script is still available as well.


Primes.is_prime(1)     // => false
Primes.is_prime(2)     // => true
Primes.is_prime(13)    // => true
Primes.at(0)           // => 2
Primes.at(1)           // => 3
Primes.at(5)           // => 13

Advertisement

Leave a reply on "JavaScript: Finding primes"

Feel free to express your opinions, remarks, comments, ideas, observations, notes, interpretations, thoughts, love or hate here. You can even use Textile to format your comments, some nice shortcuts are built in into the toolbar below.

Concerning spam: don't provide links to your website if it's completely irrelevant, I will remove links to websites that for instance provide loans or cheap insurances. Please also write your comment in clear English, not in some gibberish English no one really understands. Comments are filtered by Spam Karma 2 to prevent all kinds of spam.

(This will not be published.)

Textile controls (requires JavaScript):