1.1 计算质数(判断输入)
首先我们要明确质数(素数)的含义:
所谓质数(素数),是它的因数只有1与它本身,例如2。
所以我们可以这样判断一个数是否为质数:
# -*- coding: UTF-8 -*- # 用户输入数字 num = int(input("请输入一个数字: ")) # 质数大于 1 if num > 1: # 查看因子 for i in range(2,num): if (num % i) == 0: print(num,"不是质数") print(i,"乘",num//i,"是",num) break else: print(num,"是质数") # 如果输入的数字小于或等于 1,不是质数 else: print(num,"不是质数")
这样子是不是很简单?
1.2 计算质数(质数表之print)
那么有可能有人要问了:我要做质数表怎么办呢?
其实就是上面的程序在加一个for循环就好了:
# -*- coding: UTF-8 -*- def prime(num): for i in range(2,num): if (num % i) == 0: break else: print(num,"是质数") for i in range(2,100002): prime(i) input()
1.3 计算质数(质数表之写入文件)
为了便于以后查看,我们把它写入到文件中:
# -*- 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,"是质数") a.write(str(num)+"是质数"+'\n') for i in range(2,100002): prime(i) input()
2.1 计算完全数(完全数表之写入文件)
所谓完全数,就是一个数的因子之和(不包括它本身)等于它,例如6。
要用Python计算完全数,还要了解梅森素数。即
如果这个数为素数,则称之为 “梅森素数”)。
这是一个梅森素数列表:
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]
完全数公式:
其中
为梅森素数。
寻找完全数程序:
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()
结束语
到此这篇关于利用Python计算质数与完全数的文章就介绍到这了,更多相关Python计算质数与完全数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/PC789/article/details/114454584