zoukankan      html  css  js  c++  java
  • 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

     执行:

  • 相关阅读:
    可视化数据库管理工具DataGrip使用详解
    MySQL常用函数
    你必须掌握的 21 个 JAVA 核心技术!
    idea中那些好用到飞起的插件
    Object使用
    单页面应用和多页面应用的区别及优缺点
    正则常用匹配
    npm --save-dev 和 --save 的区别
    js常用小技巧
    js复制文字到剪切板
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/3829974.html
Copyright © 2011-2022 走看看