赞
踩
“素数一般指质数。质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。”下面通过python代码计算出200以内的质数。
- if __name__ == '__main__':
- # 初始化一个列表
- primes = [2]
- # 从2开始遍历200以内的数字
- for number in range(2, 200):
- for prime in primes:
- # 对number进行取余操作
- remainder = number % prime
- if remainder == 0: # The number is not prime
- break
- sqrt = number ** 0.5
- if sqrt < prime:
- primes.append(number)
- break
- # m = sqrt(n) ------> m*m = n, if n is not prime, n = a * b
- # a * b = m * m
- # 1.a > m, b < m
- # 2.a = m, b = m
- # 3.a < m, b > m
- # min(a,b) <= m
- print(primes)
运行结果为:
[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]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。