'Why is my prime number checking code not displaying the correct output?
I have a code that checks whether a number is prime or not, and outputs "Yes" or "No" accordingly. But when I input 1763, it outputs "Yes" even though it isn't a prime. The code checks whether a number is prime or not by checking if it can be divisible by any number between 2 and n-1. So when I input 1763, it should output "No" because 1763 can be divisible by 41. What went wrong in my code?
def getNumber():
n=int(input())
return n
def isPrime(n):
if n==2:
print("Yes")
else:
for i in range (2,n):
if n%i==0:
print("No")
break
else:
print("Yes")
break
def main():
n = getNumber()
isPrime(n)
main()
Solution 1:[1]
In your loop you break on the first iteration, even if you haven't been able to prove that it isn't a prime yet.
You need to print yes only after you've checked all possible divisors up to n (it's actually enough to only check all numbers upp to the square of n).
for i in range (2,n):
if n%i==0:
print("No")
return
print("Yes")
Solution 2:[2]
You should declare a number to be a prime only after you iterate through all the possible divisors without finding one. For that you can use the for-else construct instead, where the else block is only executed if the for loop isn't aborted with a break statement:
def isPrime(n):
if n==2:
print("Yes")
else:
for i in range (2,n):
if n%i==0:
print("No")
break
else:
print("Yes")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
