1.1 計(jì)算質(zhì)數(shù)(判斷輸入)
首先我們要明確質(zhì)數(shù)(素?cái)?shù))的含義:
所謂質(zhì)數(shù)(素?cái)?shù)),是它的因數(shù)只有1與它本身,例如2。
所以我們可以這樣判斷一個(gè)數(shù)是否為質(zhì)數(shù):
# -*- coding: UTF-8 -*-
# 用戶(hù)輸入數(shù)字
num = int(input("請(qǐng)輸入一個(gè)數(shù)字: "))
# 質(zhì)數(shù)大于 1
if num > 1:
# 查看因子
for i in range(2,num):
if (num % i) == 0:
print(num,"不是質(zhì)數(shù)")
print(i,"乘",num//i,"是",num)
break
else:
print(num,"是質(zhì)數(shù)")
# 如果輸入的數(shù)字小于或等于 1,不是質(zhì)數(shù)
else:
print(num,"不是質(zhì)數(shù)")
這樣子是不是很簡(jiǎn)單?
1.2 計(jì)算質(zhì)數(shù)(質(zhì)數(shù)表之print)
那么有可能有人要問(wèn)了:我要做質(zhì)數(shù)表怎么辦呢?
其實(shí)就是上面的程序在加一個(gè)for循環(huán)就好了:
# -*- coding: UTF-8 -*-
def prime(num):
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,"是質(zhì)數(shù)")
for i in range(2,100002):
prime(i)
input()
1.3 計(jì)算質(zhì)數(shù)(質(zhì)數(shù)表之寫(xiě)入文件)
為了便于以后查看,我們把它寫(xiě)入到文件中:
# -*- coding: UTF-8 -*-
def prime(num):
a = open('prime.txt','a')
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,"是質(zhì)數(shù)")
a.write(str(num)+"是質(zhì)數(shù)"+'\n')
for i in range(2,100002):
prime(i)
input()
2.1 計(jì)算完全數(shù)(完全數(shù)表之寫(xiě)入文件)
所謂完全數(shù),就是一個(gè)數(shù)的因子之和(不包括它本身)等于它,例如6。
要用Python計(jì)算完全數(shù),還要了解梅森素?cái)?shù)。即
如果這個(gè)數(shù)為素?cái)?shù),則稱(chēng)之為 “梅森素?cái)?shù)”)。
這是一個(gè)梅森素?cái)?shù)列表:
lst = [2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,6972593,13466917,20996011,24036583,25964951,30402457,32582657,37156667,42643801,43112609,57885161,74207281,77232917,82589933]
完全數(shù)公式:
其中
為梅森素?cái)?shù)。
尋找完全數(shù)程序:
import time
c = 0
lst = [2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,6972593,13466917,20996011,24036583,25964951,30402457,32582657,37156667,42643801,43112609,57885161,74207281,77232917,82589933]
xx = open('perfect.docx','w')
time_start=time.time()
for i in lst:
c += 1
a = (2**(i-1))*(2**i-1)
xx.write(str(c)+':'+str(a)+'\n')
time_end=time.time()
print(str(c)+' complete numbers have been calculated, it takes %s seconds.'%str(time_end-time_start)+'This m is '+str(i)+',it has '+str(len(str(a)))+' digits.')
input()
結(jié)束語(yǔ)
到此這篇關(guān)于利用Python計(jì)算質(zhì)數(shù)與完全數(shù)的文章就介紹到這了,更多相關(guān)Python計(jì)算質(zhì)數(shù)與完全數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 使用Python判斷質(zhì)數(shù)(素?cái)?shù))的簡(jiǎn)單方法講解
- python求質(zhì)數(shù)的3種方法
- python實(shí)現(xiàn)挑選出來(lái)100以?xún)?nèi)的質(zhì)數(shù)
- Python 判斷是否為質(zhì)數(shù)或素?cái)?shù)的實(shí)例
- Python編程求質(zhì)數(shù)實(shí)例代碼
- python輸出100以?xún)?nèi)的質(zhì)數(shù)與合數(shù)實(shí)例代碼
- Python 2種方法求某個(gè)范圍內(nèi)的所有素?cái)?shù)(質(zhì)數(shù))
- 解決Python中回文數(shù)和質(zhì)數(shù)的問(wèn)題
- python求質(zhì)數(shù)列表的例子
- python中判斷數(shù)字是否為質(zhì)數(shù)的實(shí)例講解