今日看到一个思路简单的判断是否为素数的方法,记录于此:
def count_factors(n):
"""Return the number of positive factors that n has.
>>> count_factors(6)
4 # 1, 2, 3, 6
>>> count_factors(4)
3 # 1, 2, 4
"""
i, count = 1, 0
while i <= n:
if n % i == 0:
count += 1
i += 1
return count
def is_prime(n):
return count_factors(n) == 2 # only factors are 1 and n
用例如下:
n = [1, 3, 5, 8, 11, 12, 13]
for i in n:
print(is_prime(i))
'''
False
True
True
False
True
False
True
'''