我正在尝试编写一个程序,告诉您数字是否为素数。这里是。正如您在运行chkPrime
函数时所看到的,一切都返回true。我为我的生活无法弄明白。有任何想法吗?
total=0
#Check if number is whole
def chkWhole(x):
if(x%1 == 0):
return True
else:
return False
#Check to see if the number divides evenly with all primes
def chkModtwo(n):
a=n%2
if chkWhole(a)==True:
return True
else:
return False
def chkModthree(n):
a=n%3
if chkWhole(a)==True:
return True
else:
return False
def chkModfive(n):
a=n%5
if chkWhole(a)==True:
return True
else:
return False
def chkModseven(n):
a=n%7
if chkWhole(a)==True:
return True
else:
return False
#Check if the number is a prime using other two functions
def chkPrime(n):
if n== 1 or 2 or 3 or 5 or 7:
return True
if chkModtwo(n)==False and chkModthree(n)==False and chkModfive(n)==False and chkModseven(n)==False:
return True
else:
return False
#while True:
#yourinput=raw_input("Enter to check if it is a prime")
#
#
# youranswer=chkPrime(yourinput)
#
# if youranswer==True:
# print("Yes, it is a prime")
# else:
# print("No, this number is not prime")
答案 0 :(得分:5)
if n== 1 or 2 or 3 or 5 or 7:
应该是
if n == 1 or n == 2 or n == 3 or n == 5 or n == 7:
或
if n in (1, 2, 3, 5, 7):
答案 1 :(得分:1)
当您的功能试图确定143是素数还是复合时,您的功能如何响应?
以下是我在my blog编写此函数的方法。
def isPrime(n):
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
答案 2 :(得分:1)
尝试:
import math
def isPrime(x):
prime = True
if x%2 == 0:
Prime =False
else:
for i in range(2,math.sqrt(x)):
if a == i:
pass
else:
a%i == 0:
Prime = False
break
return Prime
if isPrime(x):
print('prime')
else:
print('Not prime')
答案 3 :(得分:-2)
def prime():
a=int(raw_input("enter the no : "))
if a == 1:
print "the no is not prime"
elif a == 2:
print "the no is prime"
else:
for i in range(2,a):
if a%i == 0:
return "the no is not prime"
else:
return "the no is prime"
prime()