1. 程式人生 > >Python實現素數篩法與二分查詢(遞迴)

Python實現素數篩法與二分查詢(遞迴)

def prime(n):
    if n<=2:
        return []
    result=[False,False]+[True]*(n-2)
    for i in range(len(result)):
        if result[i]==True:
            for j in range(2*i,len(result),i):
                result[j]=False
    return [i for i in range(len(result)) if result[i]==True]
def bi_search(prime,primelist,start,end):
    if start>end :
        return -1
    mid=(start+end)//2
    if primelist[mid]==prime:
        return mid
    elif primelist[mid]>prime:
        end=mid-1
    else:
        start=mid+1
    return bi_search(prime,primelist,start,end)
if __name__=='__main__':
    n=int(input())
    primelist=prime(n)
    num=input()
    while num:
        num=int(num)
        index=bi_search(num,primelist,0,len(primelist)-1)
        print(index)
        num=input()