6. is_prime is frustrating me


#1

Okay. So I have tried everything. I have read through other questions and their solutions. I have added a flag. And nothing is working. I used to be able to get all the way to 4 without getting a logic error. So here's the code I have so far.

def is_prme(x):
    flag = 0
    if x < 2:
        flag = 0
    else:
        for n in range(2, x-1):
            if x % n != 0:
                flag = 1
            else:
                flag = 0
    if flag == 0:
        return False
    elif flag == 1:
        return True

I know the flag variable isn't technically necessary, but it was the only way for me to get anything returned at all.

Please Help Me


#2

Hi,
First of all, let's fix the type in the first line:

to def_is_prime(x): :wink:

The next issue would be:

You shouldn't put it there, but indent it under the else, to control if the flag 1 or 0 after the loop, but only if it's 2 or greater than 2.

The next thing is, that you check if x % n is != 0 and change the flag to 1, but the loop goes on and so does the flag change. For example I use 9, so it will check through 9/2, 9/3, 9/4 and so on. So the flag will only take the last result of the modulo calculation.


#3

Okay. So I have fixed the first few issues you mentioned. I see what you mean by the flag variable changing after each iteration. I'm not sure exactly how to fix that. Currently, my code is:

def is_prime(x):
    if x == 0:
        return False
    if x < 2:
        return False
    else:
        flag = 0
        for n in range(2, x-1):
            if x % n != 0:
                flag = 1
            else:
                flag = 0
        if flag == 0:
            return False
        elif flag == 1:
            return True

The response I get is "Oops, try again. Your function fails on is_prime(2). It returns False when it should return True." I tried switching around the true and false positions, and I get the same, but is_prime(4) responds true when it should return false. I'm wondering if I could take out the flag variable, because it is semi-redundant, but it is the only way I can get the code to return anything at all.

Thank you for helping me. I appreciate the time you have taken to look and correct my code.


#4

Alright. I have figured out what I have done wrong. Thank you for your comments. I really appreciate it.


#5

You're welcome
Glad if I could help :smiley: