python判断素数的方法
1 #运用python的数学函数 2 3 import math 4 5 def isPrime(n): 6 if n <= 1: 7 return False 8 for i in range(2, int(math.sqrt(n)) + 1): 9 if n % i == 0: 10 return False 11 return True 12 13 #单行程序扫描素数 14 15 from math import sqrt 16 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 import count 23 def isPrime(n): 24 if n <= 1: 25 return False 26 for i in count(2): 27 if i * i > n: 28 return True 29 if n % i == 0: 30 return False 31 32 #不使用模块的两种方法 33 34 def isPrime(n): 35 if n <= 1: 36 return False 37 i = 2 38 while i*i <= n: 39 if n % i == 0: 40 return False 41 i += 1 42 return True 43 44 45 def isPrime(n): 46 if n <= 1: 47 return False 48 if n == 2: 49 return True 50 if n % 2 == 0: 51 return False 52 i = 3 53 while i * i <= n: 54 if n % i == 0: 55 return False 56 i += 2 57 return True