Reputation: 175
I was curious about prime numbers and would like to know the most efficient way to find relatively small prime numbers for a range up to say, 10 million. I read that the sieve of erastosthenes (SOE) is the most efficient way to find smaller prime numbers. I implemented SOE using python but had a few questions:
The worst case running time of my algorithm seems to be O(n^2). I'm still learning, so I know this algorithm can be made more efficient.
Is there a difference in the most efficient mathematical way and most efficient programming way to find prime numbers? Mathematically, SOE is one of the fastest, but programming-wise is SOE all that fast?
def FindPrime(n):
primes = [2, 3]
for num in range(4, n):
notprime = False
for p in primes:
if num % p == 0:
notprime = True
if notprime == False:
primes.append(num)
print primes
print FindPrime(100)
Upvotes: 2
Views: 6912
Reputation: 51863
uʍop ǝpısdn is right your code is not SOE
you can find mine SOE implementation here
complexity of mine implementation of SOE
T(0.5·n·DIGAMMA(CEIL(SQRT(n))+0.3511·n)
if the sqrt(N) is used like suggested in comment inside codeT(3.80*n)
T(4.38*n)
T(4.95*n)
T(5.53*n)
T((0.3516+0.5756*log10(n))*n)
O(n.log(n))
difference between speed (runtime) and complexity O()
t=T(f(n))*c
t=O(f(n))*c
O()
is the time complexity of algorithmT()
is actual run time equation for any n (not O()
!!!)c
is some constant time which is needed to process single pass in all for
s together etc...O()
does not mean faster solutionn
only after treshold whereO1(f1(n))*c1 < O2(f2(n))*c2
c
constant then you can beat better complexity algorithms up to a tresholdT(n.n/2)
-> O(n^2)
O(n.log(n))
So for the question if there is difference between most efficient math and programing solution
Upvotes: 0
Reputation: 77029
First of all, you should know that your algorithm isn't the sieve of Eratosthenes. You're using trial division.
There are a number of improvements that can be made to your implementation.
Use xrange()
, which is O(1)
memory-wise, not range()
, which is O(n)
.
Skip even numbers in your search: xrange(4, n, 2)
steps 2 at a time.
Don't test if a prime p
divides n
when p > sqrt(n)
. It is not possible.
As you predicted, these changes don't affect the order of complexity, but you'll see a solid performance improvement.
As for a faster algorithm, first implement a real sieve of Eratosthenes, then try the much faster sieve of Atkin.
Upvotes: 4