1. 程式人生 > >python指令碼11_求10萬以內所有素數

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:

#求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:

#求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)

 

比較兩種演算法的效率:

#兩種演算法的對比的完整程式碼 

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")