简体   繁体   中英

Validate if input number is prime

Trying to write a program that checks if a number is prime. Wrote the below code, but do not understand why do I have an output of 2 lines:

num = int(input("Provide number to check if prime: "))
if num <=1:
    print("Invalid choice, try again")
    num = int(input("Provide number to check if prime: "))

for i in range(2,num):
    if num% i ==0:
        print("Number is not prime")
        break
    if num %i !=0:
        print("Number is prime")

My output is:

Provide number to check if prime: 15
Number is prime
Number is not prime

The sympy.isprime () is a built-in function under the SymPy module and can be utilized for checking of possible prime numbers. It is a direct function and returns True if the number to be checked is prime and False if the number is not prime.

>>> import simpy
  
>>> sympy.isprime(8)

False

>>> sympy.isprime(11)

True

or else define a function like this

>>> def isPrime(k):
    
    # 1 is not prime number
    if k==1:
        return False

    # 2, 3 are prime
    if k==2 or k==3: 
        return True

    # even numbers are not prime
    if k%2==0: 
        return False

    # check all numbers till square root of the number , 
    # if the division results in remainder 0
    # (skip 2 since we dont want to divide by even numbers)

    for i in range(3, int(k**0.5)+1, 2):
        if k%i==0:
            return False

    return True

>>> print(isPrime(13))

True

>>> print(isPrime(18))

False

As the first thing, you should remember that 1 isn't a prime number by definition, even if it can't be divided by any other number:

if (num == 1):
    print("The number is NOT prime")
else:
    for i in range(2, num):
        if (num%i == 0): # If the number has a divisor
            print("The number is NOT prime")
            break
    else: # If the for loop ends without reaching any break
        print("The number IS prime")

The else branch of a for loop is reached when the loop ends without reaching any break AND the loop executes at least one time.

To better understand my answer, I would suggest to read this .


The error with your solution is caused by the loop printing that the number is prime for each time num%i == 0 , so taking num = 6 :

6%4 != 0 # The number is prime
6%5 != 0 # The number is prime             

As Rajarshi Ghosh suggested, you should know that while programming it's a good idea to use import ed functions to do this simple operations, in order to avoid long operations for such a simple job.

If you don't want to use an imported function, I would suggest you to read this article where they explained 6 ways of finding if a number is prime without using functions made by others.

You have issues in output, not only for the case of 15 , but also for cases smaller than 1 . The following code should work. It has two improvements.

  1. It prints the correct output for 15. The key is to move the else block to align with the for loop.
  2. It prints the correct output for any number smaller than 1, which is not prime. The key is to use the while-break method to get user enter right number until it is bigger than 1.
num = int(input("Provide number to check if prime: "))
while num <=1: #you need to use while loop
    print("Invalid choice, try again")
    num = int(input("Provide number to check if prime: "))
    if num > 1: #only evaluate number is prime or not if it is greater than 1
        for i in range(2,num):
            if num% i ==0:
                print("Number is not prime")
                break
        else: #to move the `else` block to align with the `for` loop.
            print("Number is prime")
        break #add a break here

Output:

在此处输入图像描述

What is a while loop? A while loop tests the input condition. Every time the loop finishes, the condition is reevaluated (only evaluate number is prime or not if it is greater than 1). As long as the the number entered is <=1 , the loop keeps executing (keep asking users for input).

If you want to just check whether a number is prime or not just do the following:

num = int(input("Provide number to check if prime: "))

flagNotPrime = False

if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            flagNotPrime = True
            break

if flagNotPrime:
    print("Number is not prime")

else:
    print("Number is prime")

Firstly, numbers that are <= 1 are not prime numbers. Therefore, the above code only proceeds if the num is greater than 1.

Secondly, the code checks if num is exactly divisible by any number from 2 to num - 1 . If there is a factor in that range, the number is not prime, so the flag is set to True and the loop is broken using break .

Lastly, outside the loop, if the flag is True then num is not prime.

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