n = 100
num = [2,4,6,7]
def prime(x):
"""get the sorted prime number that is smaller than x"""
def is_div(a,b):
if b*b > a : return 0
if a%b == 0 : return 1
return is_div(a,b+1)
def is_prime(n):
return n>=2 and not is_div(n,2)
lst = []
for i in range(2,x):
if is_prime(i):
lst.append(i)
return lst
def bi_search(l,x):
"""get the index of x in prime(n),if do not have x, return -1"""
l = list(l)
if len(l) == 0 : return -1
mid = len(l) / 2
if x == l[mid][1]:
return l[mid][0]
elif x > l[mid][1]:
return bi_search(l[mid+1:],x)
elif x < l[mid][1]:
return bi_search(l[:mid],x)
if __name__ == "__main__":
l = prime(n)
for i in num:
print bi_search(enumerate(l),i)