Need help!: Is my logic wrong for prime number?


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#


The code isn't working properly for numbers like 4,9...


def is_prime(x):
    if x<2:
        return False
    elif x==2:
        return True
    else:
        
        for i in range(2,x):
            if x%i==0:
                prime=0
            else:
                prime=1
        if prime ==1:
            return True
        else:
            return False


#2

As that loop runs, it will change prime between 0 and 1 several times, back and forth, should it really do that? Your whole loop is equivalent to the if-statement below, since the last iteration determines the value of prime in your loop

if x % (x-1) == 0:
    prime = 0
else:
    prime = 1

#3

Your reply just made me realize the mistake @ionatan :slight_smile:
I missed a break statement...
Here's the code with the fix

def is_prime(x):
    if x<2:
        return False
    elif x==2:
        return True
    else:
        for i in range(2,x):
            if x%i==0:
                prime=0
                break
            else:
                prime=1
        if prime ==1:
            return True
        else:
            return False

#4

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