Exercise for Hedy and Andy

Check if it is prime We should come back to this one over and over again. It is a hard problem.


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)


False
False
True

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)


Error-----last one:  999 False True

In [3]:
all(prime_checker1(i)==prime_checker2(i) for i in range(1,10000))


Out[3]:
True

In [13]:
from timeit import timeit
print timeit(lambda:prime_checker1(177372),number= 1000)
print timeit(lambda:prime_checker2(177372),number= 1000)


2.73137116432
19.0169608593

In [11]:
prime_checker1(17737)


Out[11]:
True

using While loop


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]:
True

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)


1.87202000618
15.4128699303
0.0714960098267

In [ ]: