Is prime - Can't understand how this isn't working


#1



Hi guys

This is my first ever post so please be patient if it's not quite structured how it should be, thanks.

So I've taken care of numbers 2 and 3 with simple if statements. Then for 4 and every other number above 3 I've set up a for loop with a nested while loop testing if x can be divided evenly.

The error message states that when x = 4 it is returning none when of course it should return true;

"Oops, try again. Your function fails on is_prime(4). It returns None when it should return False."

I think the while loop is getting stuck and not progressing to the else statement which I could understand if the else function was part of the if statement, however it is outside of the if statement and is part of the for loop, therefore it shouldn't get stuck. I've also tried indenting the else statement under the while loop but to no avail. Otherwise I have no idea as to what could be going wrong here. Any suggestions?

def is_prime(x):
    if x < 2:
        return False
    if x == 2 or x == 3:
        return True
    else:
        for n in range(x - 1, 2):
            while n > 1:
                if x % n == 0:
                    return False
            else:
                return True

Many thanks


#2

I did it a little differently:

def is_prime(x):
    if x < 2:
        return False
    elif x == 2 or x == 3:
        return True
    else:
        n = 2
        while n < x:
            mod = x % n
            if (mod == 0):
                return False
                break           #if n divides into x evenly, we know it's not a prime number so it returns False and breaks
            else:
                n += 1    # if n does not divide into x, the loop continues
                if n == (x - 1):    # if the loop reaches the point where n = x-1 without breaking, we know there is no divisor
                    return True    # if there is no divisor, the function returns true

Hope this helps.


#3

I chose slightly different approach and decided to use "for" loop as I found it simpler. I also think that we needn't assert that 3 is a prime as the program will evaluate it. And I think that there is no need to put "break" command after "return False" as the program will stop anyway.

And my solution goes as follows:

def is_prime(x):
    if x < 2: # anything less than 2 is not  a prime
        return False
    elif x == 2
        return True
    else:
        for i in range(2,x):
            if x % i == 0:
                return False
            else:
                if i == x-1:
                    return True

I belive this solution may help, too.


#4

Brilliant, thanks very much, still not sure how mine doesn't work but your solution makes complete sense and works, cheers =D


#5

Great, thanks very much =D


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.