The following code will print the prime numbers between 1 and 100. Modify the code so it prints every other prime number from 1 to 100


In [9]:
skip=False # 1 is, by definition, not a prime number, so we will start with 2 
           # and skip every other result after that
for num in range(2,101): 
    prime = True 
    for i in range(2,num): 
        if (num%i==0): 
            prime = False 
    if prime:
        if skip:
            skip=False
        else:
            print(num)
            skip=True


2
5
11
17
23
31
41
47
59
67
73
83
97

Extra Credit: Can you write a procedure that runs faster than the one above?


In [19]:
# to test for primes, we actually only need to test for divisibility by all previously discovered primes
# this version will perform far fewer mod operations
primes=[]
for num in range(2,101): 
    prime_test = True 
    for prime in primes: 
        if (num%prime==0): 
            prime_test = False 
    if prime_test:
        primes.append(num)
print(primes)


[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]

In [ ]: