赞
踩
1 #运用python的数学函数
2
3 importmath4
5 defisPrime(n):6 if n <= 1:7 returnFalse8 for i in range(2, int(math.sqrt(n)) + 1):9 if n % i ==0:10 returnFalse11 returnTrue12
13 #单行程序扫描素数
14
15 from math importsqrt16 N = 100
17 [ p for p in range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]18
19
20 #运用python的itertools模块
21
22 from itertools importcount23 defisPrime(n):24 if n <= 1:25 returnFalse26 for i in count(2):27 if i * i >n:28 returnTrue29 if n % i ==0:30 returnFalse31
32 #不使用模块的两种方法
33
34 defisPrime(n):35 if n <= 1:36 returnFalse37 i = 2
38 while i*i <=n:39 if n % i ==0:40 returnFalse41 i += 1
42 returnTrue43
44
45 defisPrime(n):46 if n <= 1:47 returnFalse48 if n == 2:49 returnTrue50 if n % 2 ==0:51 returnFalse52 i = 3
53 while i * i <=n:54 if n % i ==0:55 returnFalse56 i += 2
57 return True
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。