+ 1
What's wrong with my prime number function?
5 ответов
+ 5
Baran Aldemir, you wrote:
if number is divisible
not prime
else
prime
This means that the first number that is no divisor will already say it's a prime and end the search.
But you have to check if there is *not any* divisor, only then you'll know it's prime.
Say, the number 14.
Divisible by 3 will be False. So: prime.
But 14 is divisible by 7 - it's no prime! But you stop checking already at 3.
That's why have to wait till after the loop.
+ 4
This is a corrected version of your function.
def is_it_prime(number):
if(number <= 1):
print ("{} is not a prime number".format(number))
# After you got a result
# you need to abort the function
return
elif(number == 2):
print ("{} is a prime number".format(number))
# same here
return
else:
for i in range(2,number):
if (number % i == 0):
print ("{} is not a prime number".format(number))
return # instead of break
# This was in the loop before
# But only after all numbers
# have been checked, you can
# know if it's prime
print ("{} is a prime number".format(number))
+ 1
HonFu
You said
#But only after all numbers have
#been checked, you can
# know if it's a prime
Why is that?
If I find any number (except for 1 and my main number itself) divides my main number without remainder, it means my main number is not a prime number. Otherwise it should be a prime number.
Is my logic wrong?
+ 1
HonFu Okay okay you meant the loop. Got it. Thanks a lot.👍