import math
def generate_primes(limit):
"""Generates and prints a list of primes up to a given limit"""
prime_list = [2, 3]
num = 5
increment_2 = True # When True increment by 2. When False increment by 4
while num <= limit:
is_prime = True
sqr_lim = math.sqrt(num)
for x in prime_list:
# Loop through list of prime numbers and check divisibility
if x > sqr_lim:
break
if num % x == 0:
is_prime = False
break
if is_prime:
# Add primes to list to only check prime numbers
prime_list.append(num)
# Alternate step size between 2 and 4 to skip multiples of 2 and 3
if increment_2:
num += 2
increment_2 = False
else:
num += 4
increment_2 = True
print(prime_list)
return prime_list
def main():
generate_primes(200)
if __name__ == "__main__":
main()
I'm writing a program to generate a list of prime numbers to a given limit through the use of trial division. I was wondering if there is a way to further optimize this code. Currently it: skips multiples of 2 and 3; stores primes in a list and the list is used to check for primality; and checks divisibility up until the square root of the number it's analyzing.
I would also appreciate it if someone could critique me on my coding style such as comments, white space, and organization because I know its pretty rough around the edges. Thanks for the help.