narn - 1 year ago 109

Python Question

I know that this question was asked way too many times, but I'm not searching for the fastest algorithm. I'd only like to know what I'm doing wrong with my code since it's faulty.

`import math`

def is_prime(number):

for i in range (2, 1+ int(math.sqrt(number))):

if number % i == 0:

return 0

else:

return 1

choice = int(input("Check if it's prime: "))

if is_prime(choice):

print ("{} is a prime number".format(choice))

else:

print ("{} is not a prime number".format(choice))

If I test this program for most numbers it will return correct response, but if I check any square number it will say that it's a prime. So any suggestions what I'm doing wrong?

Answer Source

You are returning immediately in the first iteration of the loop ... always.

Instead only return immediately when you know it is not a prime, else keep going:

```
def is_prime(number):
for i in range (2, 1+ int(math.sqrt(number))):
if number % i == 0:
return 0
return 1
```