Advertisement
vaboro

ps1a.py

Apr 18th, 2012
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1.  
  2. ##################################################################################################################################
  3. # Note, that the first prime in the set of primes is 2. Therefore, when we start checking the next prime candidate by dividing   #
  4. # it by all the previous primes, the first prime we divide the cadidate by is 2 and, thus, first, we check if the number is even #
  5. # or odd. If it's even, then the candidate is rejected and we start checking the next candidate.                                 #
  6. ##################################################################################################################################
  7.  
  8. import math
  9.  
  10. Primes = [2] #stores all computed primes
  11.  
  12. NumberOfPrimes = len(Primes) #holds the number of primes in the list Primes
  13.  
  14. while NumberOfPrimes < 10000:
  15.    
  16.     n = Primes[NumberOfPrimes - 1] + 1 #next prime candidate
  17.  
  18.     i = 0
  19.  
  20.     while i < len(Primes) and Primes[i] <= int(math.sqrt(n)): #divide the cadidate by all the previous primes up to the square root of the candidate
  21.        
  22.         #print "Prime candidate",n,"i is",i
  23.  
  24.         if n % Primes[i] == 0:
  25.  
  26.             n = n + 1          #if there's a remainder choose the next candidate
  27.            
  28.             i = 0              #reset counter to start checking from the beginning of the set of primes
  29.            
  30.         else:
  31.  
  32.             i = i + 1 #continue checking primality of the candidate with next prime in the set of primes
  33.  
  34.     Primes.append(n) #the candidate couldn't be divided without remainder by any of the previous primes, the candidate is prime, append it to the list
  35.  
  36.     NumberOfPrimes = len(Primes) #update the number of primes
  37.  
  38. print "The 1000th prime is", Primes[999]
  39. #print "The 2000th prime is", Primes[1999]
  40. #print "The 3000th prime is", Primes[2999]
  41. #print "The 4000th prime is", Primes[3999]
  42. #print "The 5000th prime is", Primes[4999]
  43. #print Primes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement