Reputation: 37
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.
Upvotes: 3
Views: 209
Reputation: 2699
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.
Upvotes: 1
Reputation: 19885
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.
Upvotes: 3