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

yipeiwu_com5年前Python基础

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

作为学习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 <= n:
    if myArray[startPos] == 1:
      resultList.append(startPos)
    startPos += 1
  return resultList

numString=raw_input("Input the Range(>3):")
numInt=int(numString)
if numInt <= 3:
  print "The Number Need to be greater than 3"
else:
  primeResult=primeRange(numInt)
  print "The Result is:",primeResult

相关文章

pytorch:实现简单的GAN示例(MNIST数据集)

我就废话不多说了,直接上代码吧! # -*- coding: utf-8 -*- """ Created on Sat Oct 13 10:22:45 2018 @author: w...

Python中列表、字典、元组、集合数据结构整理

本文详细归纳整理了Python中列表、字典、元组、集合数据结构。分享给大家供大家参考。具体分析如下: 列表:复制代码 代码如下:shoplist = ['apple', 'mango',...

基于Python log 的正确打开方式

保存代码到文件:logger.py import os import logbook from logbook.more import ColorizedStderrHandler...

详解Python中的装饰器、闭包和functools的教程

装饰器(Decorators) 装饰器是这样一种设计模式:如果一个类希望添加其他类的一些功能,而不希望通过继承或是直接修改源代码实现,那么可以使用装饰器模式。简单来说Python中的装饰...

对python For 循环的三种遍历方式解析

实例如下所示: array = ["a","b","c"] for item in array: print(item) for index in range(len...