Is_prime what's wrong?


#1



is_prime


What's wrong with my code?


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


#2

Hi,

someone had a similar problem the other day:

Also while n > 2 doesn't work because n is only defined inside of the for-loop.
Did you mean if x > 2: ? If so you also have to handle the cases where x <= 2. You don't need to handle negative numbers.


#3

Thanks for your help, it works now.


#4

You simply need to define the "0" and "1" cases before the loop since they are special numbers that obeys to the prime numbers rule but are not prime:

def is_prime(x):
    
    
    
    if x==1 or x==0:
        return False
        
    n=2

    while n!=x:
        if (x%n)==0:
            return False
        if x>n:
            n+=1
        else: 
            n-=1
      
    else:
        return True

#5

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