孪生素数是指相差为2的素数对,比如3和5,5和7,11和13,输出n以内的素数对个数
n < 1000000
定义子函数 + 分隔判断
class Solution: def getres(self, n): if not n: return 0 count = 0 for index in range(2, n): if index + 2 == n: break num1, num2 = index, index + 2 if self.isSatisfied(num1) and self.isSatisfied(num2): count += 1 return count #判断是否是素数 def isSatisfied(self, num): for j in range(2, num - 1): if num % j == 0: return False return True res = Solution().getres(1000) print(res)
执行结果: