简体   繁体   中英

Checking for prime numbers: Any number is prime?

Hello dearest community,

I'm stuck on something very easy, I guess sometimes your just out of it. Anyhow, I wrote this to check for prime numbers:

num = int(input(""))

if num > 1:
    for i in range(2, num-1):
        if (num % i)  == 0:
            print(num, "is no Primenumber")
            break
        else:
            print(i, "PRIME!!!")

(The original code doesn't print anything, but I had trouble with it, so I rewrote it for debugging purposes)

Anyway, it correctly identifies non prime numbers, but prints out this for prime numbers, lets say 7:

7
2 PRIME!!!
3 PRIME!!!
4 PRIME!!!
5 PRIME!!!

If you are concerned with performance for larger numbers it is better to use square root over number flooring division 2 . Any number that is a factor greater than the square root will also have 1 that is less.

Here's a common solution:

def check_for_prime(p_in):
    is_prime = True
    for n in range(2, int(p_in ** 0.5) + 1):
        if p_in % n == 0:
            is_prime = False
            break
    return is_prime

num = int(input(""))

if check_for_prime(num):
    print(f'{num} is prime')
else:
    print(f'{num} is not prime')

Not the most performance conscious, but will get the job done and is simple.

n = input("Enter a number to check if it is prime [returns True or False]: ")
n = int(n)

if n < 2:
    quit()

if all(n % i for i in range(2, n)):
    print(n, "PRIME!!!")

Use the below logic to find the number is prime or not. This is suited for python, as there is an else block for the for loop which gets exectued when the loop is not broken during execution which mean the number is prime.

if num > 1: 

   # Iterate from 2 to n / 2  
   for i in range(2, num//2): 

       # If num is divisible by any number between  
       # 2 and n / 2, it is not prime  
       if (num % i) == 0: 
           print(num, "is not a prime number") 
           break
   else: 
       print(num, "is a prime number") 

else: 
   print(num, "is not a prime number") 

Without third-party module, you can easily perform it this way:

def is_prime(number):
    return all(number % n for n in range(2, number))

This way, you check:

  • all division between the specified number, and any number between 2 and the one before the number
  • the trick is to consider the fact that if any number % n gives 0, which means it is a multiple, so it can't be a prime number, and you will get a result immediately

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