我的质数检查器认为 15 是质数

My prime number checker thinks 15 is a prime number

num = int(input("Number: "))
returned = False
if num > 1:
    for i in range(2, (num - 1)):
        if (num%i) > 0 and returned == False:
            returned = True
            print(f"{num} is a prime number")
        elif (num%i) == 0 and returned == False:
            returned == True
            print(f"{num} isn't a prime number")
else:
    print(f"{num} is neither a composite number or a prime number")

这段代码 returns 15 是一个质数,而且还有很多其他问题。不懂电脑在想什么

{更新}

我相应地更新了代码,现在可以正常工作了


quit = ''

while quit != "q":
    n = int(input("Enter the number: "))
    is_prime = True
    limit = n - 1
    if n > 1:
        for i in range(2, limit):
            if (n%i) == 0:
                is_prime = False
                print(f"{n} isn't a prime number...")
                break
    if is_prime and n > 1:
        print(f"{n} is a prime number...")
    elif n == 1:
        print("The number is neither a composite or a prime...")
    elif n == 0:
        print("This is not a prime number, this is your exams result.")
    quit = input("(q)uit or (n)o: ")
    if quit == 'n':
        print("continuing")

假设您输入的数字是 15。 已经在循环的第一次迭代中 (i=2) 您的 if 语句等于 true,因为 15%2 = 1 大于 0,因此您执行 print(f"{num} is a prime number")

更好的实现方式是:

num = int(input("Number: "))
is_prime = True
for n in range(2,int(num**0.5)+1):
    if num%n==0:
        is_prime = False
        print(f"{num} isn't a prime number")
if is_prime:
    print(f"{num} is a prime number")

您可能需要查看 % 运算符

num = int(input("Number: "))
isPrime = True
if num > 1:
  for i in range(2, (num - 1)):
    if (num%i) == 0:
      isPrime = False
      print(f"{num} isn't a prime number")
      break
  if (isPrime):
    print(f"{num} is a prime number")
else:
  print(f"{num} is neither a composite number or a prime number")