1. 程式人生 > >關於質數(素數)

關於質數(素數)

 

 

素數的演算法:

最基礎的演算法:

n = int(input('>>>'))
for i in range(2, n):
    if n % i == 0:
        print(n, '可以被', i, '整除')
        break
else:
    print(n, '是一個質數')

改進演算法,通過開方縮小整除範圍:

n = int(input('>>>'))
for i in range(2, int((n**0.5)+1)):
    if n % i == 0:
        print(n, '可以被', i, '整除')
        break
else:
    print(n, '是一個質數')

通過剔除偶數再次縮小計算範圍

n = int(input('>>>'))
for i in range(3, int((n**0.5)+1),2):
    if n % i == 0:
        print(n, '可以被', i, '整除')
        break
else:
    print(n, '是一個質數')

引入datetime模組來統計演算法耗時

import datetime
start = datetime.datetime.now()
print(2, end=', ')
count = 1
for i in range(3, 100000, 2):
    for j in range(2, int((i**0.5)+1)):
        if i % j == 0:
            break
    else:
        count += 1
        # print(i, end=', ')
delta = (datetime.datetime.now() - start).total_seconds()
print(delta)


引入time模組來統計演算法耗時 

import time
start = time.clock()
# print(2, end=', ')
count = 1
for i in range(3, 100000, 2):
    for j in range(2, int((i**0.5)+1)):
        if i % j == 0:
            break
    else:
        count += 1
        # print(i, end=', ')
end = time.clock()
delta = end - start
print(delta)

列印10萬以內的所有質數

print(2, end=', ')
for i in range(3, 100000, 2):
    for j in range(2, int((i**0.5)+1)):
        if i % j == 0:
            break
    else:
        print(i, end=', ')

演算法改進,刪除所有大於10之後,最後一位是5的數字

import time
start = time.clock()
count = 1
for x in range(3, 100000, 2):
    if x > 10 and x % 10 == 5:
        continue
    for i in range(3, int(x ** 0.5) + 1, 2):
        if x % i == 0:
            break
    else:
        count += 1
end = time.clock()
delta = end - start
print(count)
print(delta)

演算法改進,與6取模(沒搞懂這個演算法的原理,先加上吧),

import time
start = time.clock()
count = 1
for x in range(3, 100000, 2):
    if x % 6 != 1 and x % 6 != 5:
        continue
    for i in range(3, int(x ** 0.5)+1, 2):
        if x % i == 0:
            break
    else:
        count += 1
end = time.clock()
delta = end - start
print(count)
print(delta)

通過引用列表來改進程式碼

另外演算法改進

import time
ls = [2]
start = time.clock()
for i in range(3, 100000, 2):
    for j in ls:
        if i % j == 0:
            break
    else:
        ls.append(i)
end = time.clock()
print(end - start)
print(ls)

引入math模組

import math
import time
ls = []
start = time.clock()
count = 0
flag = False
for x in range(2, 100000):
    for i in ls:
        if x % i == 0:
            flag = True
            break
        if i >= math.ceil(math.sqrt(x)):
            flag = False
            break
    if not flag:
        ls.append(x)
        count += 1
end = time.clock()
print(end - start)
print(count)