Python函数检查数字是否为素数
def is_prime(num):
lst = []
if num > 1:
pass
else:
return False
for number in range(0, 1000000+1):
if str(num) in str(number):
continue
elif str(1) in str(number):
continue
elif str(0) in str(number):
continue
lst.append(number)
for x in lst:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
print(is_prime(9))
我不知道我的代码有什么问题,我找不到解决方案,程序的重点是检查数字是否是素数(素数只能被 1 和它本身整除)。for 循环似乎不起作用或什么的
回答
def isprime(n):
return (all([False for i in range(2,n) if n % i == 0 ]) and not n < 2)
print (isprime(0))
print (isprime(1))
print (isprime(2))
print (isprime(3))
print (isprime(9))
print (isprime(10))
print (isprime(13))
输出:
False
False
True
True
False
False
True
或者:
def isprime(n):
if n < 2: return False
for i in range(2, n):
if n % i == 0:
return False
else:
return True
- The first version thinks 2 is not prime and the second one thinks 0 and 1 are prime