简体   繁体   中英

Why is my prime number function not working?

I am new to programming and I face an issue while trying to write a program in finding out prime number. Here is my code:

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

I received an error stating "Your function fails on is_prime(3). It returns None when it should return True."

Can someone please explain the flaw in this code?

Thank you!

range() has an exclusive upper bound , so it's trying to get the range between 2 and 2 (3 - 1), which is no elements. Since you can't iterate over nothing, the for loop never runs, so None is returned (this is the default return type of a function if none is specified).

The solution to your immediate problem would be to use range(2, x) rather than range(2, x - 1) . You'll find that you'll have problems at x > 3 though because as @khelwood said, you're returning True or False immediately after checking the first value. Instead, only return True after checking all values in the range.

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        for n in range (2,x): # range function will iterate till x-1
            if x % n == 0:
                return False
        # return true only at the end after making sure it is not divisible by any number in the middle
        return True

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