For programs like this, recursion is not a very good idea. Calling a function, even itself, is one of the slower things in programming because of the stack control. You will find that in the faster prime algorithms repeated function calls are absent.
Here is an example of one of the fastest algorithms. Notice that it only has three function calls, range() is called twice and filter() is called once ...
def fast_primes(n):
"""
uses an Eratosthenes sieve to return a list of
prime numbers from 2 to < n
"""
siv = range(n+1)
siv[1] = 0
sqn = int(n**0.5)
for i in range(2, sqn+1):
if siv[i] != 0:
siv[2*i:n//i*i+1:i] = [0]*(n//i-1)
return filter(None, siv)
For n = 10000000 it takes about 4 seconds. Once you get close to one billion your memory resources start complaining.
vegaseat
DaniWeb's Hypocrite
Moderator
5,976 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,416