Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Generate Prime Numbers Up To A Given Limit
- # Mike Kerry - Jan 2021 - acclivity2@gmail.com
- # This is a pretty fast algorithm for generating prime numbers
- # "Sieve of Eratosthenes" is faster, but requires a lot of memory when generating a lot of primes
- def genPrimes(topnumber):
- # Initialise a list of primes with the first prime number, which is 2
- plist = [2]
- # Now we will look for prime numbers in the given range
- # We only need to look at add numbers from 3 up, so we use a step value of 2, starting from 3
- for n in range(3, topnumber + 1, 2):
- # We only need to test with divisors up to the square root of the number we are checking
- sqrt = n ** 0.5
- # We only need to use already discovered primes as our divisors
- for div in plist: # extract one prime number from our growing list
- if div > sqrt: # if it's greater than the square root of the number we are checking ...
- # ... then all the needed checks have been done and n is prime
- plist.append(n) # add n to our growing list of primes
- break # break out of inner loop to go get next number to test
- if not n % div: # if div divides into n with no remainder, then n is not prime
- break
- return plist # Return the completed list of primes to the calling code
- res = genPrimes(127)
- print(*res)
- # 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
Add Comment
Please, Sign In to add comment