This generator is like most where it brute forces an integer: it see whether the integer is divisible by any of the primes; if so, then it's not a prime and vice versa. This though only compares values
6n + 1 and
6n - 1 starting with
n as 1 as all primes larger than 3 can be written as
6n + 1 or
6n - 1 where
n is a positive integer.
Examples: 7 is
6(1) + 1 (
n = 1) and 17 is
6(3) - 1 (
n = 3).
primes = [2, 3] limit = 0 n = 1 is_prime = True while True: try: limit = int(raw_input("Enter a positive integer larger than 3: ")) except ValueError: print "Please enter a positive integer larger than 3!" else: if limit <= 3: print "Please enter a positive integer larger than 3!" else: break while True: minus_prime = 6*n - 1 plus_prime = 6*n + 1 if minus_prime < limit: for x in primes: if minus_prime % x == 0: is_prime = False break if is_prime: primes.append(minus_prime) is_prime = True elif minus_prime > limit: print primes break if plus_prime < limit: for x in primes: if plus_prime % x == 0: is_prime = False break if is_prime: primes.append(plus_prime) is_prime = True elif plus_prime > limit: print primes break n += 1
Basically, given preset primes 2 and 3, find all primes that are less than
limit by producing numbers with
6*n + 1 and
6*n - 1 (
n increases by one every loop) and checking first if they are over the limit. If so, stop the loop and print out the primes (as a list). If not, brute force through
primes to see if the number is prime. If so, add to
primes. Else, continue.
limit is checked in the first
while loop to ensure validity.
I am wondering how to improve the performance of my program, improve its structure, and make it more Pythonic. Try it here