# this program will test numbers and check if they are prime numbers or even numbers
num = eval(input('Enter a number: '))#generating user input
for i in range(num):
x = 2
if num % 2 == 0: #test for even numbers
print(num, x, 'is even')
else:
while num % x != 0:#the idea here is to enter a loop and test the numbers against x=2, x +=1... to check if they are divisible
x += 1 #by x
break
if num % x == 0: #x is however either 2 or 3. it never advances to four and numbers like 25 become prime numbers
print(num,x, 'is odd')
else:
print(num,x, 'is prime')
num -=1
代码中存在逻辑缺陷我无法弄清楚它在哪里
答案 0 :(得分:0)
改变这个:
num = eval(input('Enter a number: '))
要:
num = input('Enter a number: ')
if num.is_digit(): #evaluate if is a number
num = int(num)
else:
#broke code logic
num = 0
答案 1 :(得分:0)
您可以使用以下方法更快地测试素数:
List
在您的代码中:
num > 1 and all(num % i for i in xrange(2, sqrt(num)))
答案 2 :(得分:0)
你的基本问题在于这个块:
while num % x != 0:
x += 1
break
...你有一个无条件break
,这意味着循环永远不会运行多次。比较
def is_prime(n):
if n < 4:
return n in {2, 3}
elif not n % 2:
# even
return False
else:
return all(n % div for div in range(3, int(n ** 0.5 + 1.), 2))
然后您的程序看起来像
def main():
print("Show all primes up to what number?")
upto = int(input(": "))
for n in range(2, upto + 1):
if is_prime(n):
print("{} is prime".format(n))
else:
print("{} is {}".format(n, ["even", "odd"][n % 2]))
main()