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()
Related
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.
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
I wrote a piece of code to check whether a number is a prime or not. It works in Powershell, but won't work on the online submission platform.
I have re-read how to define whther a number is prime and I can't find anything else that I might have missed in my code.
x = int(input('Please enter a number: '))
if x > 1:
for i in range(2, x):
if (x % i) == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
break
else:
print('The number you inputted is not a prime number.')
Should print out whether a number is prime or not.
You can use the for-else construct so that a prime number is only determined when the loop finishes without breaking due to finding a divisor. Also, you only need to iterate up to the square root of the input number when looking for a divisor:
x = int(input('Please enter a number: '))
for i in range(2, int(x ** .5) + 1):
if x % i == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
Well, first of all you have to remove the innermost else clause.
Think in the case that x = 9, for example. Control flow will enter the for clause, starting with i=2. It will test if x % i == 0, that is, if x is divisible by i. It isn't. Then you go to the else clause. Prints that "The number you inputted is a prime number" and breaks, ending the for loop. That is not what you want.
You only conclude that the number is prime after looking if it is divisible by all of the i's. That is, you want the code concluding the number is prime (the print("The number you inputted is a prime number")) to be outside the for loop.
Some tweaks are needed overall. Here is a working solution:
x = int(input('Please enter a number: '))
if x > 1:
for i in range(2, x):
if (x % i) == 0:
print('The number you inputted is not a prime number.')
break
if i==x-1:
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.'
x = int(input('Please enter a number: '))
if x > 1:
for i in range(2, x):
if (x % i) == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.')
This correction worked!
Solution
Here's a solution modeled after the way you tried the code. Note that sometimes, if you copy a code from certain websites, you could run into code formatting issues/problems with indentation. For example, when I copied a similar code-block from programiz.com: prime-number it repeatedly returned indentation error. The only way I could get around that is hand typing the code logic.
Perhaps one could try fixing this by copy pasting the code into a plain-text-editor (like notepad) and then copy-pasting that into the IDE you are using.
def is_prime(num):
isprime = False
# prime numbers are greater than 1
if (num>1):
for i in range(2,num):
# check if divisible by any number
# other than itself and 1
if (num % i) == 0:
isprime = False
break
# Not divisible by any number
# other than itself and 1
else:
isprime = True
# numbers 0 and 1 are not prime numbers
else:
isprime = False
return isprime
is_prime(31), is_prime(42)
Output:
(True, False)
I would like to suggest a more pythonic way:
x = int(input('Please enter a number: '))
if x<2:
print('The number you inputted is not a prime number.')
elif x==2:
print('The number you inputted is a prime number.')
else:
y = range(2,x)
mod = map(lambda a:divmod(x,a)[1],y)
if all(mod):
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.')
What about removing that else statement. You really need to check all numbers 2 ... (k-1)
x = int(input('Please enter a number: '))
if x > 1:
is_prime = True
for i in range(2, x - 1):
if (x % i) == 0:
is_prime = False
break
if is_prime:
print('The number you inputted is a prime number.')
else:
print('The number you inputted is not a prime number.')
else:
print('The number you inputted is not a prime number.')
i wrote this program to check weather the no. is prime or not but it shows the number is prime multiple times. how can i solve it
To check weather the number is prime or not.
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
Here is my code to check whether a number is prime or not, hope it helps
# Program to Check whether given number is prime
def isPrime(number):
limit = int(number/2) # limit indicates how many times we need to run the loop
flag=0 # to keep track whether the number is prime or not
if number==0 or number==1:
print(f"The Given Number {number} is Not Prime")
return
for i in range(2,limit+1):
if number%i==0:
flag=1
break
if flag==0:
print(f"The Given Number {number} is Prime")
else:
print(f"The Given Number {number} is Not Prime")
isPrime(1)
Your problem is that the else part of your for-loop is wrong. You print "the number is prime" every time a division check fails, not just at the end.
I added an isPrime boolean that tracks if a single check failed. Only if none of them fail, you can print that the number is prime.
num = int(input("please enter the number you want to check\n"))
if num > 1:
isPrime = True
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
isPrime = False
break
if isPrime:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
You can simplify that even more, with a construct of python called for-else (credits to #TheGamer007):
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
It works because Python's for-loops can have an else: following, which only triggers if you don't break out of the loop.
This might be exactly what you were trying to do. In that case, all you did wrong was your indentation.
Also, from an algorithmical point of view, there are much better ways to check. A first simple improvement is that you don't need to check range(2,num), but only range(2, int(math.sqrt(num))+1)
All you need in order to determine whether a number is prime or not, is to find 1 number that is greater or equal to 2 that divides the number.
In your loop, you print out a message that says "the number is prime" for each number that does not divide the given number.
For example, if you want to check whether the number 9 is prime or not, you will loop all numbers from 2 to 8 and check if they can divide 9. So in your for loop, the number 5 for instance -> 9%5 != 0 -> "the number is prime" message will pop up, which is wrong.
The code below shows how you can use a boolean to rise up a flag when the number is NOT prime.
num = int(input("please enter the number you want to check\n"))
isPrime = True
while num < 1:
int(input("enter a positive value\n"))
if num == 1:
print("the number is not prime")
return
for i in range(2, num):
if (num % i) == 0:
isPrime = False
break
print(str(num) + " is prime? " + str(isPrime))
Use a variable, for example flag and initialize it to 0. If the number is not prime,i.e i%2==0 set flag to 1 and break, else flag = 0 .
After that come out of the for block, and with the help of if condition display the number is prime or not. That is if flag==0 the number is prime else not.
I would suggest the following implementation
We only need to check/loop up to a square root of the number and not the number itself and is thus faster.
The for-else structure gets you rid of the isPrime flag that you otherwise need. The way this works is that if the loop finishes normally without breaking (meaning you haven't found what you are looking for) it goes into the else
import math
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, int(math.sqrt(num))+1):
if (num % i) == 0:
print("the number is not prime")
print(i, "times", num//i, "is", num)
break
else:
print("the number is prime")
else:
print("the number is not prime")
One way to do it:
def is_prime(n):
count = 0
if x > 1:
for i in range(1, n + 1):
if x % i == 0:
count += 1
return count == 2
number = int(input("Insert a number: "))
if is_prime(number):
print(str(number) + " is a prime number")
else:
print(str(number) + " is not a prime number!")
is_prime(7) # >> Returns True
How does it work:
A prime number (n) must fullfill the following rules:
n > 1;
n divisible only to 1 and itself(
n % 1 == 0,
n % n == 0)
Perform the modulus operation from 1 to n iteratively. Increment the variable count
every time the result is 0. If the input satisfies the 2nd condition from above then count should be equal 2. If count equals 2 then the number is prime.
Ex:
is_prime(7): 7 % 1 = 0 (count += 1), 7 % 2 = 1, 7 % 3 = 1, 7 % 4 = 3, 7 % 5 = 2, 7 % 6 = 1, 7 % 7 = 0 (count += 1); >> 7 is prime
i have exactly 5 days of practise, an hour daily so kindly forgive if my questions are very low level. No prior coding exp
My objective of the below code is
1- check if entered number is a prime
2- if not print the next biggest prime
def primetest (num): # check if number is a prime
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting an output. Please help
The way you have done has a lot of errors not efficient. By making some modification to your code i have made it much simpler. Read the comments to understand:
def primetest (num): # check if number is a prime
return(all(num % i for i in range(2, num)))
num = int (input ("enter a number:")) # main code:
while True: #loop continues until prime number found(True)
if primetest(num):
print(num,"is a prime number.")
break #(stops loop if prime found)
else: #otherwise repeat by incrementing to the next num until found
print(num,"is not a prime number.")
num += 1
Output:
enter a number:45
45 is not a prime number.
46 is not a prime number.
47 is a prime number.