简体   繁体   中英

Stuck in an infinite loop with my prime number finder program

I've been working on a program for my class for a bit. It is supposed to be a prime number finder, where the def is_prime (num) function loops and continually asks the user to input more numbers, checks whether they are prime, and prints whether they are or not. If a negative number is entered, it is supposed to then quit.

def is_prime (num):
  while num >= 0:
    if num % 1 == num or num % num == 0:
      print(num, "is a prime")
    elif num % 2 == 0:
      print(num, "is not a prime")
      continue
    elif num < 0:
      print("Done. Thanks for using the program!")
      break
  return 0


if __name__ == "__main__":
  print("This program checks if a given number is a prime number\n")
  num1 = int(input("Please enter a positive number (or a negative number to exit):\n"))
  is_prime(num1)

However, it only has part of that right. It reads and determines prime numbers...but instead of looping back to the function beginning it just endlessly prints the statement of whether or not it is a prime. I'm pretty sure it's a problem of where I've put my while loops, but I'm not entirely sure how to fix that. Any help would be appreciated.

You haven't described your intended algorithm; it's not at all clear from your code. YOur first if checks whether the input number is divisible by 1 or divisible by itself ... both of which are algebraic tautologies.

Then you repeat this as long as the input remains positive. Since you never change the value of num , this is a pretty direct infinite loop.

You can't test for divisibility for each candidate factor with a different if in an if ladder.

You'll need to stash each prime you find in a list.

EG:

def sieve_primes(stop=100000):
    """Yield primes below stop."""
    primes = [2]
    for candidate in range(3, stop + 1, 2):
        if not any(candidate % prime == 0 for prime in primes):
            primes.append(candidate)
            yield candidate


for prime in sieve_primes():
    print(prime)

Raid it for ideas, but don't copy it verbatim. You could speed it up a lot with math.sqrt(), BTW.

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM