Is it Prime?


#1

I am trying to write a faster program for checking if a number n is prime by only checking the range (2, n**0.5) instead of going all the way to n.

So far I have but it returns True for 99. What am I doing wrong?

def is_prime(x):
    if x < 2:
        return False
    elif x == 2 or x == 3:
        return True
    else:
        for n in range(2, int(x**0.5)):
            if x % n == 0:
                return False
            else:
                return True
print is_prime(99)

#2

you start the for loop ...
in the first loop - it tests if 99%2 == 0, which evaluates to false.
then the else-branch isexecuted and voila -> return True :grin:

 for n in range(2, int(x**0.5)):
            if x % n == 0:                 # <-- 99%2 == 0          ---> false
                return False
            else:                             
                return True

hint for solution: think about indention of the last "return True"


#3

Got it. Thank you. 'Else' needed to be lined up with 'for'


#4

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