定义:除了1 和本身之外,不被任何数整除。 7 = 7*1 是 9 = 3*3 不是
代码:
1 #!/usr/bin/env python 2 # encoding: utf-8 3 """ 4 @author: 侠之大者kamil 5 @file: 8.素数.py 6 @time: 2016/4/9 18:25 7 """ 8 import math 9 def isPrimeNumber(n,s): 10 #for k in range(2,int(math.sqrt(n)) + 1): 11 for k in s:#s为小于n的素数的集合 12 if k * k > n:break#保证k 小于n的平方根,for k in range(2,int(math.sqrt(n)) + 1) 13 if n % k ==0 : return None # 14 return n 15 prime=[] 16 for n in range(2,300): 17 res = isPrimeNumber(n,prime) 18 if res: 19 prime.append(res) 20 print(prime)
结果:
ssh://[email protected]:22/usr/bin/python3 -u /home/kamil/py22/趣味百题/8.素数.py [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293] Process finished with exit code 0
时间: 2024-10-01 06:57:30