开发者

This my script that check a number is prime or not, but when the number is 99 or 77, the scripyt failed to check, why? how to fix it?

开发者 https://www.devze.com 2023-01-23 08:41 出处:网络
num = input(\"Please enter an integer: \") def is_Prime(): h = num / 2 for x in range(2, h +1):开发者_StackOverflow社区
num = input("Please enter an integer: ")
def is_Prime():
    h = num / 2
    for x in range(2, h +1):开发者_StackOverflow社区
        if (num%x) == 0:
            return False
    return True
def main():
    if is_Prime():
        print num, "is a prime number"
    else:
        print num, "is not a prime number"
main()


You are always returning true or false after checking divisibility with 2:

for x in range(2, h + 1):
    if (num%x) == 0:
        return False  # <<< here
    else:
        int(h) != h
        return True   # <<< and here

Also I'm not sure what the line int(h) != h is supposed to do. You are evaluating an expression and then discarding the result.

Try this instead:

for x in range(2, h + 1):
    if (num % x) == 0:
        return False
return True

Regarding the line h = num / 2 the upper limit of num / 2 will work, but actually you only need to check up to math.sqrt(num).


Try this:

def is_Prime():
    h = num / 2
    for x in range(2, h +1):
        if (num%x) == 0:
            return False
    return True


You seem to have fixed the problems with your script with your edit. However, there a few more things you could improve.

You should really be passing the number you're testing to the function, rather than accessing at as a global variable.

The call to input() should really be inside the main() function.

Also, you can simplify your loop by using the all function:

def is_Prime(num):
    h = num / 2
    return all(num % x != 0 for x in range(2,h+1))
0

精彩评论

暂无评论...
验证码 换一张
取 消