I’m completely stuck with this lesson. For some reason I can’t get this code working. Has anybody some suggestions on what I’m doing wrong. Thanks in advance!
VBR Patrick
def is_prime(x):
result = [] #Stores the result
count = x #To divide x by
while count - 1 > 1:
test = x % (count-1) #Calc if x is prime
count -= 1
result.append(test) #Stores the result
for i in result: #Check if num is composite by looking for evidence in the results
if i == 0:
return False
break
else:
if x < 2:
return False
else: # if the num is prime
return True
Try this it should work because it stores all the reusults rather than one at a time. Just sub var count for the var n in your case
def is_prime(x):
if x>2 :
n=x
while n>2:
if x%(n-1)==0:
return False
break
else :
n -= 1
else:
return True
elif x==2:
return True
else :
return False
Try this instead I made it to where the while statement checks for a composite no. and added an else saying if the while is no longer true (meaning the no. is not composite) then return true (since a non-composite no. greater that 0 is prime)
My working solution is below. It loops through every number from 2 up to -x to check whether it is not prime, and if none of the options succeed it finishes the loop returning True. The problem I believe you are having with you code and the problem I had doing this before is that you aren’t going through every number to check, it just stops at the first one that it calculates. Remember that anything after a return statement doesn’t get calculated.
def is_prime(x):
n = 2
if x < 2:
return False
else:
while n < x:
if x % n != 0:
n += 1
else:
return False
else:
return True
Your code when ran might be a bit problematic because of the control flow, using two else statement that don’t account for any secondary conditions is unnecessary when you can just simplify your code with an if and else statement.
I realised the first else statement is useless, however im sure you are referencing the 2 at the end. Im dont really understand what you are trying to explain, could you change my code to be simpler in the way you suggested?
if use this cod I have problem which negative numbers… ""Oops, try again. Your function fails on is_prime(-10). It returns None when it should return False. “”
May be any know about fix it ?.. thanks