6/15 is_prime


#1

Hi,

I have some problems with my code.

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

I hope you can help me.

Thanks. :sweat_smile:


#2

@yukardo can you repost your code formatted

if you want to format your code when you paste it here you have three options

  1. select the code (after you paste it here) and press ctrl + k or
  2. select the code(after you paste it here) and press </> in the tools pane
  3. put this character ` three times at the begining and end of code

#3
def is_prime(x):
    div = 0
    flag = True
    if x <= 0 or x == 1:
        return False
    elif x == 2:
        return True
    else:
        for n in range(2, x - 1):
            print "Number: %i divider: %i" % (x, n)
            div = x % n
            if div == 0:
                flag = False
                break
            else:
                flag
    return flag

#4

For the line " for n in range(2, x - 1)", put "for n in range(2, len(x) - 1).


#5

Here's another way...

    
def is_prime(x):
        n = 2
        prime = True
        if x < 2:
            prime = False
        else:
            while n < x:
                if x % n == 0:
                    prime = False
                    break
                else:
                    n += 1
        return prime