Skip to content
Advertisement

Fastest way to list all primes below N

This is the best algorithm I could come up.

JavaScript

Can it be made even faster?

This code has a flaw: Since numbers is an unordered set, there is no guarantee that numbers.pop() will remove the lowest number from the set. Nevertheless, it works (at least for me) for some input numbers:

JavaScript

Advertisement

Answer

Warning: timeit results may vary due to differences in hardware or version of Python.

Below is a script which compares a number of implementations:

Many thanks to stephan for bringing sieve_wheel_30 to my attention. Credit goes to Robert William Hanks for primesfrom2to, primesfrom3to, rwh_primes, rwh_primes1, and rwh_primes2.

Of the plain Python methods tested, with psyco, for n=1000000, rwh_primes1 was the fastest tested.

JavaScript

Of the plain Python methods tested, without psyco, for n=1000000, rwh_primes2 was the fastest.

JavaScript

Of all the methods tested, allowing numpy, for n=1000000, primesfrom2to was the fastest tested.

JavaScript

Timings were measured using the command:

JavaScript

with {method} replaced by each of the method names.

primes.py:

JavaScript

Running the script tests that all implementations give the same result.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement