您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python实现高效求解素数代码实例

2025/12/4 15:38:50发布20次查看
素数是编程中经常需要用到的。
作为学习python的示例,下面是一个高效求解一个范围内的素数的程序,不需要使用除法或者求模运算。
#coding:utf-8 #设置python文件的编码为utf-8,这样就可以写入中文注释def primerange(n): myarray=[1 for x in range(n+1)] ##列表解析,生成长度为(n+1)的列表,每个数值都为1 myarray[0]=0 myarray[1]=0 startpos=2 while startpos <= n: if myarray[startpos]==1: key=2 resultpos = startpos * key #可知startpos的整数倍都不是素数,设置startpos的整数倍的位置为0表示非素数 while resultpos <= n: myarray[resultpos] =0 key += 1 resultpos = startpos *key startpos += 1 resultlist=[] ##将最终的素数保存在resultlist列表返回 startpos=0 while startpos 3):)numint=int(numstring)if numint <= 3: print the number need to be greater than 3else: primeresult=primerange(numint) print the result is:,primeresult
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product