Prime number checker should be working but its not [duplicate] - python

This question already has answers here:
Prime number check acts strange [duplicate]
(14 answers)
Closed 5 days ago.
I'm writing a program that tells if this is a prime number from the input.
I'm trying to understand the logic of this code:
def prime_checker(number):
for i in range(2, number):
if number % i == 0:
print("It's not a prime number.")
break
else:
print("It's a prime number")
break
n = int(input("Check this number: "))
prime_checker(number=n)
Previously, I did not put a break, which resulted with a lot of print statements being printer. So I googled, "how to end the loop in python".
Now, the code did not work as expected. For example, if I put 2, I get no results (nothing). If I put 87, it says it's a prime number (it's not).
Can someone explain what is wrong with the code?
I know that the right solution would be:
def prime_checker(number):
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
if is_prime:
print("It's a prime number.")
else:
print("It's not a prime number.")
n = int(input("Check this number: "))
prime_checker(number=n)
However, I do want to truly understand the logic and differences between two. Any thoughts?
Many Thanks!

You cannot know whether number is a prime before having checked all potential divisors. So you cannot expect to know the number is a prime before the loop has made all* iterations. You really need to be sure there is no integer divisor.
The opposite is true: you can know whether the number is not a prime before having tested all potential divisors, because you only need to find one divisor. As soon as you found it you know it is not a prime and don't need to continue looping. The second code could therefore be optimised by a break just following is_prime = False
* Well, you could know once i > sqrt(number). Fact is that the loop doesn't have to continue beyond that limit.

Related

Making a program in Python that tells if a number is a prime number, or not a prime number [duplicate]

This question already has answers here:
Prime number check acts strange [duplicate]
(14 answers)
Closed last month.
Im new here, hopefully i can ask question that is okey to ask here, but i've been fighting last hours with Python, im trying to make a program as simple as possible to tell the user if the number they choose to write in is a prime number or not a prime number.
Thing is, i managed to make it work, then somehow i did'nt save it so lost it.
My code so far
n = int(input("Enter a number: "))
for i in range(2, n):
if (n%i == 0):
break
quit (str(n) + " is not a prime number")
print (n, "is a prime number")
This makes my program tell the user that whatever number that is choosen, it will say "is a prime number"
Before i did'nt have the break function there, i added it and changed something else and it worked somehow.
Any idea?...
Im very new to programming, python is my second language.
I expect that the program to tell user to enter a number from number 2 to 101 if a number is a prime number it will print in console or a not a prime number and print it.
My idea:
The program starts by asking for an integer. Then a for loop starts with a range from the number 2, up to 100. Once inside the loop, do the same check as we did in the Scratch program, that is, check if the number n modulo i = 0 where i starts at two and count up to the number we entered (but not including the number we entered). If we get an answer here that gives 0 in the remainder, then it is not a prime number and this is printed on the screen with the text "is not a prime number" and at the same time ends the program. If no answer is given where we get 0 in the remainder, then it is a prime number and the number together with the text "is a prime number" is instead printed on the screen.
I wish i could just ask a friend, but lets give this forum a shot!
Let me know if this kind of question is not suitable in this forum!
Take care
Chris
There are couple of issue with your code. your break statement supressing the not prime print statemnt. Your print prime number is excluded from any loops hence it is printed every time.
Code correction
n = int(input("Enter a number: "))
for i in range(2, int(n/2)+1):
if (n % i) == 0:
print(n, "is not a prime number")
break
else:
print(n, "is a prime number")
More simpler approch
n = int(input("Enter a number: "))
result = all(n % i for i in range(2, n))
if result:
print(n, 'prime num')
else:
print(n, 'not a prime num')

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 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.

Have some doubts in this python program (PRIME or NOT)

So, I wrote a code to find if a number is PRIME or NOT...
I wrote it in 2 different ways, they are almost same but I just had a doubt. So here it is:
1st code:
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
2nd Code:
num = int(input("Enter the number: "))
for i in range(2,num):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
The 1st code takes the input(num) and according to the input sets a limit(which is the half number + 1)
and then checks if the num is divisible by all the numbers in range (2 to lim)
The second one is same but instead of setting a limit it just checks all numbers lower than the input, which means it has to do a little more work...
Now both of these are almost same, the only difference is I saved a line in 2nd one and output efficiency is also better!
Which code would you want me to prefer/
also if this code has any problems, pointing them out would be helpful!
Thanks :)
Explanation
The most important piece of iteration, namely determining whether a number is prime or not, is to keep track of it. Without this process and in the OP's program, a variable is not used to handle this, meaning that he checks whether a number is or isn't prime every single time and concludes at that point. He also uses an else statement which is syntactically incorrect.
To prevent this, we can use a variable to keep track of this. Let's call it isprime. We need to assume that a number will always be a prime unless otherwise said. This can be achieved by setting isprime to default be True, and setting it to be False when we conclude that it is not a prime, because is has a divisor. Finally, we can check this variable at the end and determine whether that number is a prime or not, because it would be set to False if not, or left as True if it is.
Another observation made is that the limit for determining primes can be reduced down to sqrt(n). This is because we do not need to find every factor if it exists, just its lowest corresponding factor. Let's look at an example:
Factors of 24: 2, 3, 4, 6, 8, 12
We can stop checking for the factors right here:
2, 3, 4 | 6, 8, 12, 24
This is because if a number has a factor (such as greater than the square root), it will have a corresponding factor less than the square root. As a result, we can set our limit to be sqrt(n), just for peace of mind + a time complexity of O(sqrt(n)) v. O(n).
As an extra note, sqrt is not inbuilt into Python. You will have to import it from the math library using:
from math import sqrt
Final Code
# Setup
num = int(input("Enter the number: "))
lim = sqrt(num)
isprime = True
# Loop & check
for i in range(2,lim):
if num % i == 0:
isprime = False
break
# Results
if isprime:
print("Prime!")
else:
print("Not prime!")
The logic of the solution is wrong. You gave to switch the "Prime" and "Not Prime" tags. Like follows;
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Not Prime!")
break
else:
print("Prime!")
The solution 1 is more efficient because you do not need to do extra
computation to check num//2 + 1. So it is preferable.

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.

Categories

Resources