python腳本11_求10萬之內全部素數

#求10萬之內全部素數

num = int(input(">>>"))
strs = ''

for i in range(2,num):
    for c in range(2,int(i**0.5)+1):
        if i%c == 0:
            break
    else:
        strs += str(i)+' '
print(strs)

方法2:算法

print(2)

for i in range(3,100001,2):
    if i>10 and i%10 == 5:
        continue
    else:
        for j in range(2,int(i**0.5+1)):
            if i%j == 0:
                break
        else:
            print(i)

方法3:spa

#求10萬之內全部素數
#此題的目的是爲了讓你們注意效率問題
#思考:爲何到一個數的一半就能夠了

for a in range(2,100000):
    for b in range(2,int(a**0.5)+1):
        if a%b == 0:
            break
    else:
        print(a)

 

方法4:code

#求10萬之內全部素數
#此題的目的是爲了讓你們注意效率問題

for a in range(3,100000,2):
    for b in range(3,int(a**0.5)+1,2):
        if a%b == 0:
            break
    else:
        print(a)

 

比較兩種算法的效率:blog

#兩種算法的對比的完整代碼 

import datetime

upper_limit = 100000
delta = [0,0]
counts = [0,0]

start = datetime.datetime.now()
for _ in range(10):
    count[0] = 0
    for x in range(2,upper_limit):
        for i in range(2,int(x**0.5)+1):
            if x % i == 0:
                break
        else:
            #print(x)
            counts[0] += 1
delta[0] = (datetime.datetime.now() - start).total_seconds()


start = datetime.datetime.now()
for _ in range(10):
    counts[1] = 1
    #print(2)
    for x in range(3,upper_limit,2):
        for i in range(3,int(x**0.5)+1,2):
            if x % i == 0:
                break
        else:
            #print(x)
            counts[1] += 1
delta[1] = (datetime.datetime.now() - start).total_seconds()

print(delta, sep="\t")
print(conuts, sep="\t")
相關文章
相關標籤/搜索