acclivity

pyPrimeNumberGenerator

Jan 23rd, 2021 (edited)
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. # Generate Prime Numbers Up To A Given Limit
  2. # Mike Kerry - Jan 2021 - acclivity2@gmail.com
  3.  
  4. # This is a pretty fast algorithm for generating prime numbers
  5. # "Sieve of Eratosthenes" is faster, but requires a lot of memory when generating a lot of primes
  6.  
  7.  
  8. def genPrimes(topnumber):
  9.  
  10.     # Initialise a list of primes with the first prime number, which is 2
  11.     plist = [2]
  12.  
  13.     # Now we will look for prime numbers in the given range
  14.     # We only need to look at add numbers from 3 up, so we use a step value of 2, starting from 3
  15.     for n in range(3, topnumber + 1, 2):
  16.  
  17.         # We only need to test with divisors up to the square root of the number we are checking
  18.         sqrt = n ** 0.5
  19.  
  20.         # We only need to use already discovered primes as our divisors
  21.         for div in plist:           # extract one prime number from our growing list
  22.             if div > sqrt:          # if it's greater than the square root of the number we are checking ...
  23.                                     # ... then all the needed checks have been done and n is prime
  24.                 plist.append(n)     # add n to our growing list of primes
  25.                 break               # break out of inner loop to go get next number to test
  26.  
  27.             if not n % div:         # if div divides into n with no remainder, then n is not prime
  28.                 break
  29.  
  30.     return plist                    # Return the completed list of primes to the calling code
  31.  
  32.  
  33. res = genPrimes(127)
  34. print(*res)
  35.  
  36. # Result: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127
  37.  
Add Comment
Please, Sign In to add comment