+ 1

What's wrong with my prime number function?

https://code.sololearn.com/c39ut0Ji18An/?ref=app

24th Dec 2019, 1:09 PM
Baran Aldemir
Baran Aldemir - avatar
5 Answers
+ 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.
24th Dec 2019, 3:10 PM
HonFu
HonFu - avatar
+ 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))
24th Dec 2019, 2:25 PM
HonFu
HonFu - avatar
+ 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?
24th Dec 2019, 3:03 PM
Baran Aldemir
Baran Aldemir - avatar
+ 1
HonFu Okay okay you meant the loop. Got it. Thanks a lot.👍
24th Dec 2019, 3:12 PM
Baran Aldemir
Baran Aldemir - avatar