Validate if input number is prime - python

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 imported 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.
It prints the correct output for 15. The key is to move the else block to align with the for loop.
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.

Related

i have to write a program in python to check that 3 ,11 are prime numbers whereas 9 is not

I have written this code, for that but its returning 9 as a prime number too.
when i am putting 9 as the input i am getting below output.
enter a number:9
it is a prime number
not a prime number
num = int(input("enter a number:"))
for i in range(2,num):
if num % i == 0:
print("not a prime number")
else:
print("it is a prime number")
but this is showing 9 is a prime number too
You can just break the loop inside if condition, and pull the else part out of the loop, it'll behave the way you are looking for.
Inside the loop, if the number is divisible, it means it's not a prime, and loop immediately breaks, but if it makes all the way to else part of for loop, it means that the number is prime; this else part will be executed only if the loop was not manually broken.
num = int(input("enter a number:"))
for i in range(2,num):
if num % i == 0:
print("not a prime number")
break
else:
print("it is a prime number")
PS: You don't even need to check upto n, you can just check upto √n, more information at Wikipedia Primality test

In Python, write a script that determines whether or not a user-inputted number is a prime number

Write a script that determines whether or not a user-inputted number is a prime number and prints "The number that you inputted is a prime number" or "The number that you inputted is not a prime number" depending on what your script finds.
I have code that is failing some of the test cases and I'm not sure why. I see some answers on here that involve calculate the sqrt, but I don't understand why that'd be beneficial.
num= int(input())
if num == 0 or num ==1:
print('The number you inputted is not a prime number.')
while num < 0:
break
if num > 0:
for i in range(2,num):
if num%i==0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
break
The code is always right when I try it with a few test cases, but it isn't passing my homework assignment.
Your logic is wrong; you should break only if the condition evaluates to True, since you need to test all numbers up to num ** 0.5 (num in your code). 9 is an example of a non-prime number that your code evaluates as prime.
You want something like this:
prime = True
if num > 0:
for i in range(2,num):
if num % i == 0:
prime = False
break
if prime:
print(f'{num} is a prime number.')
else:
print(f'{num} is not a prime number.')
By setting prime to True at the start and changing it to False only if a factor is found, we can tell, after evaluation of the condition for all the values of i, if the number is prime.
The problem occurs in the logic below:
for i in range(2,num):
if num%i==0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
break
To see where the issue occurs, try using your code to check if 9 is prime.
Your for loop does the following:
i = 2
if num % i == 0, not prime, break.
else, prime, break.
This means that your for loop is guaranteed to stop at i==2.
In other words, your definition for a prime number, according to this algorithm is 'any odd number'.
To fix this, you need to find a way to allow the loop to iterate between all the remaining possible divisors, without breaking after the first iteration.
I'm going to stop there, to give you a chance to see if you can figure the rest out yourself. If you can't make any progress, let me know, and I'll give another hint.

How to stop python printing more than one line?

I have a small function to check if a number is prime or not. It works fine apart from one small detail - it prints out more than one print line on the program end.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()
If I enter the number 2 for e.g. when the program runs, it prints:
the number 2 is prime
the number 2 is prime
the number 2 is prime
It only needs to print the line once, so why is this?
Your else is in the wrong position. You have it on the if, but you actually want it on the for.
It might not be well known, but you can have a else on for-loops and it will execute if no break was executed during the loops.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()

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

Why doesn't this prime number algorithm say that 2 is not prime?

Why is it that when you input 2 into this program, it returns "2 is prime"? According to the code, if the remainder of the number divided by i, where i is any number from (and including) 2 up to the number, is equal to 0, then the number is not a prime number. But the remainder of 2 divided by 2 is 0, so why does the program say that 2 is a prime number?
# Python program to check if the input number is prime or not
# take input from the user
num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
because for i in range(2,2): will never be true / will not execute.
think about it range(start, stop)... the start and stop are the same so it will not enter into the for loop.
2 is a prime number but is the one case where the if statement doesn't need to be computed to determine if its a prime number
more details about pythons range function
range(2, 2) is actually an empty list, so the for loop doesn't iterate at all. It just jumps straight to the else clause:
>>> num = 2
>>> range(2, num)
[]
>>> for i in range(2, num):
... print "executing loop"
... else:
... print "done!"
...
done!

Categories

Resources