1.输出第几个素数是多少?
def prime(n): if n <= 1: return 0 for i in range(2, math.ceil(math.sqrt(n + 1))): if n % i == 0: return 0 return 1 def Prime(n): st = 2 while n: if prime(st): yield st n -= 1 st += 1 for i in Prime(10): print(i)
结果如下
基于模拟Range实现的IntegRange,封装一个类,可以通过for循环直接打印指定范围的质数
例如:
for i in IntegerRange(2,20,1):
print(i)
可以依次打印出2,3,5,7,11...等全为质数的数字
import math class IntegerRange: def __init__(self, start, end, step): self.start = start self.end = end self.step = step # def __iter__(self): while self.start < self.end: if self.prime(self.start): yield self.start self.start += self.step def prime(self, n): if n <= 1: return 0 for i in range(2, math.ceil(math.sqrt(n + 1))): if n % i == 0: return 0 return 1 g = IntegerRange(2, 20, 1) for i in g: print(i)
结果如下