简体   繁体   中英

determining if random Int is prime or not

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM