简体   繁体   中英

Identify whether or not a number is prime

The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong?

quuN = int(input("ENTER NUMBER : "))

quuM = 2

if (quuN <= 0) :

    print("ENTER NON-NEGATIVE NUMBER PLEASE")


elif (quuN % quuM == 0) :

    print(" IS PRIME " )

else : 

    print("IS NOT PRIME ")

The logic is incorrect

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.

Simple python code below

def is_prime(n):
    for i in range(3, n):
        if n % i == 0:
            return False
    return True

The above code is checking if a number is even or odd. If you enter a prime number, for example 17, the code checks if 17 is less than or equal to 0. Then it checks 17%2 which evalutes to 1, and is not 0. Hence the else block is executed which prints IS NOT PRIME .

If you enter an even number, it prints IS PRIME.

This code checks for Prime numbers.

def is_prime(n):
    import math
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            return False
    return True

I assume you're a beginner with python so let me point out the logic to check primality of numbers in your code is not correct, you should read first carefully the definition of primes numbers , when you do so, try to understand this little example which shows you how to check prime numbers:

import math

def is_prime_naive(number):
    if number == 2:
       return True
    if number % 2 == 0:
        return False

    i = 3
    sqrt_number = math.sqrt(number)

    while i <= sqrt_number:
        if number % i == 0:
            return False
        i = i+2

    return True

for i in range(2,101):
    print "{0} {1} prime".format(i,"is" if is_prime_naive(i) else "is not")

Now, be aware the above code is one of the simplest but also slowest way to check whether a number is prime or not. When you become familiar enough with the concept of primes then you should check for fastest way to check primality, some examples could be the Fermat and Miller Rabin primality tests. So, good luck with primes, you'll sure have fun with them ;-)

Here's the answer without using any libraries

Note: it's only needed to check until sqrt(n), explanation here

def isPrime(n):
    if (n<=1): return False

    for i in range(2, int(n**(.5))+1):
        if (n%i==0):return False

    return True

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