In [21]:
from timeit import default_timer as timer
start = timer()
other = True
for num in range(1,101): # for-loop through the numbers
prime = True # boolean flag to check the number for being prime
for i in range(2,num): # for-loop to check for "primeness" by checking for divisors other than 1
if (num%i==0): # logical test for the number having a divisor other than 1 and itself
prime = False # if there's a divisor, the boolean value gets flipped to False
if prime: # if prime is still True after going through all numbers from 1 - 100, then it gets printed
if other == True:
print(num)
other = False
else:
other = True
end = timer()
exec_time_1 = end - start
print("Time:", exec_time_1)
In [115]:
from timeit import default_timer as timer
#import collections
#other_prime = collections.deque()
start = timer()
other = True
other_prime = []
for num in range(1,101):
prime = True # boolean flag to check the number for being prime
if (num & 1) == 0 and num > 2: # fast test for even numbers
continue
for i in range(2,num): # for-loop to check for "primeness" by checking for divisors other than 1
if (num%i==0): # logical test for the number having a divisor other than 1 and itself
prime = False # if there's a divisor, the boolean value gets flipped to False
break
if prime: # if prime is still True after going through all numbers from 1 - 100, then it gets printed
if other == True:
other_prime.append(num)
other = False
else:
other = True
print(*other_prime, sep="\n")
end = timer()
exec_time_2 = end - start
print("Time:", exec_time_2)
diff = (exec_time_1 - exec_time_2)/exec_time_1
if diff > 0:
print("The second code ran {0:.2f}% faster.".format(100*diff))
else:
print("The second code ran {0:.2f}% slower.".format(-100*diff))