determining if random Int is prime or not

93 views Asked by At

I have a little problem when i need to determine if a number , x is a prime number or not. x will be a randomly generated positive integer and i get the following message when i execute code:

Your function fails on is_prime(2). It returns None when it should return True.

My code:

def is_prime(x):
if x < 2:
    return False
else:
    for n in range(2, x):
        while x % n == 0:
            return False
            break
        else:
            return True

i want the while loop to iterate through n == 2 up to n == (x-1) but it doesnt seem to do it! what am i doing wrong?

1

There are 1 answers

1
Eugen Chubchik On

You could write this function much more simplier:

import math
def is_prime(n):
    if n % 2 == 0 and n > 2: 
       return False
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        if n % i == 0:
           return False
    return True

So your call for is_prime(2) wouldn't pass the if test and wouldn't be used in the for run and would just return True.

All other prime numbers should be tested if they are greater than 3 and not even.