作为学习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
