Replace this line with your code. def is_prime(x): if x == 2: return True elif x <= 1: return False else: for n in range(2, x - 1): if x // n == 0: return False break else: return True return True
-- Try using
if x % n == 0 instead of
if x // n == 0.
% is the modulus and it helps you find the remainder of a number. If the number is totally divisible by numbers other than 1 and itself, then it is not a prime. For example, 12 is not a prime. 12 % 2 == 0, 12%3 == 0.
If the number is not totally divisible by numbers other than 1 and itself, it is a prime. Say let's use 13. Regardless of the numbers getting passed in it, it won't ever be divided except by 1 and itself.
-- You can remove the
break in your
else statement in your
for loop is redundant. You can remove it and only keep the
return True outside.
-- Additionally, your code could be simplified even further.
- Any number below 2 is not a prime number.
- 2 is a prime number.
elsestatement checks numbers from the range of 2 to x - 1, where x is the number being passed into the
- Assume it's 2 being passed into the
elsestatement, it will face this
forloop which divides it from 2 to 2-1, which is an empty list
. Therefore, there is no list to iterate, so it never gets passed into the
if-elsestatement inside the
- The number 2 will therefore never go through the
forloop at all, so it will end up with
return True(2 is a prime).
What I'm getting at, is that this:
if x == 2: return True elif x <= 1: return False
can simply be:
if x < 2: return False
Thank you, I get it now
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.