In [1]:
def prime_checker1(x):
'''decide if an integer is a prime'''
for i in range(2,x):
if x%i==0: return(False)
return(True)
In [2]:
def prime_checker2(x):
'''decide if an integer is a prime'''
a=True
for i in range(2,x):
if x%i==0:
a=False
return(a)
In [21]:
def prime_checker3(x):
'''WRONG ALGORITHM--decide if an integer is a prime'''
a=True
for i in range(2,x):
if x%i==0:
a=False
else:
a=True
return(a)
In [12]:
print prime_checker1(272)
print prime_checker2(272)
print prime_checker3(272)
In [38]:
#Tester:
a=True
b=1
for i in range(1,1000):
if prime_checker1(i)<>prime_checker3(i):
a=False
b=i
if a:
print "OK"
else:
print "Error-----last one: ", b,prime_checker1(b),prime_checker3(b)
In [3]:
all(prime_checker1(i)==prime_checker2(i) for i in range(1,10000))
Out[3]:
In [13]:
from timeit import timeit
print timeit(lambda:prime_checker1(177372),number= 1000)
print timeit(lambda:prime_checker2(177372),number= 1000)
In [11]:
prime_checker1(17737)
Out[11]:
In [18]:
def prime_checker4(x):
a=2
while a< x:
if x%a==0: return(False)
a=a+1
return True
In [23]:
all(prime_checker1(i)==prime_checker4(i) for i in range(1,10000))
Out[23]:
In [28]:
print timeit(lambda:prime_checker1(17777),number= 10000)
print timeit(lambda:prime_checker2(17777),number= 10000)
print timeit(lambda:prime_checker4(17777),number= 10000)
In [ ]: