Python编程学习,高效求解素数程序实例

素数是编程中经常需要用到的。

作为学习Python的示例,下面是一个高效求解一个范围内的素数的程序,不需要使用除法或者求模运算。

 1 #coding:utf-8       #设置python文件的编码为utf-8,这样就可以写入中文注释
 2 def primeRange(n):
 3     myArray=[1 for x in range(n+1)]  ##列表解析,生成长度为(n+1)的列表,每个数值都为1
 4     myArray[0]=0
 5     myArray[1]=0
 6     startPos=2
 7     while startPos <= n:
 8         if myArray[startPos]==1:
 9             key=2
10             resultPos = startPos * key  #可知startPos的整数倍都不是素数,设置startPos的整数倍的位置为0表示非素数
11             while resultPos <= n:
12                 myArray[resultPos] =0
13                 key += 1
14                 resultPos = startPos *key
15         startPos += 1
16 
17     resultList=[]   ##将最终的素数保存在resultList列表返回
18     startPos=0
19     while startPos <= n:
20         if myArray[startPos] == 1:
21             resultList.append(startPos)
22         startPos += 1
23     return resultList
24 
25 numString=raw_input("Input the Range(>3):")
26 numInt=int(numString)
27 if numInt <= 3:
28     print "The Number Need to be greater than 3"
29 else:
30     primeResult=primeRange(numInt)
31     print "The Result is:",primeResult

 执行:

原文地址:https://www.cnblogs.com/xudong-bupt/p/3829974.html