1.运用python的数学函数
import math def isPrime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True
2.单行程序扫描素数
from math import sqrt N = 100 [ p for p in range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]
运用python的itertools模块
from itertools import count def isPrime(n): www.gxlcms.com if n <= 1: return False for i in count(2): if i * i > n: return True if n % i == 0: return False
3.不使用模块的两种方法
方法1:
def isPrime(n): if n <= 1: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True
方法2:
def isPrime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True
eg:求出20001到40001之间的质数(素数)
既然只能被1或者自己整出,那说明只有2次余数为0的时候,代码如下:
#!/usr/bin/python L1=[] for x in xrange(20001,40001): n = 0 for y in xrange(1,x+1): if x % y == 0: n = n + 1 if n == 2 : print x L1.append(x) print L1
结果如下:
20011 20021 20023 20029 20047 20051 20063 20071 20089 20101 20107 20113 20117 20123 20129 20143 20147 20149 20161 20173 ….