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




