我正在编写一个代码来确定一个数字是否为素数。这是我到目前为止收集的内容:
def isprime(p):
'''check if integer p is a prime'''
# make sure n is a positive integer
p = abs(int(p))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n = 2:
return True
# all other even numbers are not primes
if not p & 1:
return False
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
答案 0 :(得分:0)
看起来你正在尝试使用计算素数的平凡(又称慢)方法:对于素数候选p,尝试将所有整数从2分为地(sqrt(p))。
eps = 1e-9
def isprime(p):
int_p = int(p)
# only integers are prime, accounting for floating point rounding error
if abs(int_p - p) < eps:
return False
else:
# a number is prime only if it cannot be evenly divided
# by all prime factors lower than the number
return all(p % i != 0 for i in xrange(2, int(p**0.5)+1))
您之所以只想检查从3到sqrt(p)的奇数,可能是因为您知道所有大于2的偶数都不是素数。你可以做的比从这个检查中仅消除偶数更好...你只需要检查从2到sqrt(p)的素数。如果您恰好多次调用isprime
,则可以构建这些素数的缓存。还有更有效的素数算法,这取决于您尝试解决的问题(您是否正在尝试从下限到上限找到所有素数?您是否正在尝试找到素数的数量?你是吗?试图找到任何素数?)