-2

Here is the code for generating a prime number sequence. This code in particular, takes the users input as an integer (if it can), and prints out that many numbers of the prime number sequence. Is there any way to optimize this particular script so that it runs faster and can process bigger numbers at a greater speed?

P = 2
Count = 1
X = int(raw_input('choose number: '))

def Main(P, X):
    while Count <= X:
        isprime = True
        for x in range(2, P - 1):
            if P % x == 0: 
                isprime = False
        if isprime:
            print P
            Count += 1
        P += 1
Main(P, X)
supersmarty1234
  • 203
  • 2
  • 10

1 Answers1

1

n-th prime is less than N = max(12, n*(log(n) + log(log(n)))). Knowing N, you could use any solution from Fastest way to list all primes below N link provided by @Jonathan Davies.

For example, using a simple Sieve of Eratosthenes implementation, here's live example:

#!/usr/bin/env python2
from itertools import islice
from math import log

def iprimes_upto(limit):
    is_prime = [True] * limit
    for n in xrange(2, limit):
        if is_prime[n]:
           yield n
           for i in xrange(n*n, limit, n): # start at ``n`` squared
               is_prime[i] = False

n = int(raw_input('Choose number of primes to print: '))
N = max(12, int(n*(log(n) + log(log(n))) + .5)) # find limit
for p in islice(iprimes_upto(N), n): # get n primes
    print p

As an alternative, you could use an infinite prime generator (you don't need to compute the limit in this case).

Community
  • 1
  • 1
jfs
  • 346,887
  • 152
  • 868
  • 1,518