简体   繁体   中英

checking if something is a prime python?


def prime_check(num):
    if num>1:
        if num == 2:
                return True
        for i in range(2, num+1):
            if ((num%i) == 0):
                print(i)
                return False
            else:
                return True
    else:
        return False
prime_check(99)

returns true (as in is prime) when it should be false when i use value 99. WHY?

In the loop, you're returning true whenever the input is not divisible by the current number in the loop. So, in the first iteration, when if condition checks whether 99%2 == 0, if so then return false else return true . That's why it returns True as 99%2 != 0 .

Just change your code a bit, as you are using for....else :

if (num >1):
    for i in range(2, num):
        if ((num%i) == 0):
            print(i)
            return False
    else:
        return True

You can improve the program by decreasing the range of the loop using range(2,math.floor(math.sqrt(num))) :

for i in range(2,math.floor(math.sqrt(num))):
    //do the same

When 99 enters into the for loop It checks whether 99%2==0 , as it finds 99%2!=0 else block is executed, returns true and comes out of the loop without doing further iterations. You need to change the code.

To reduce the complexity you can further use sqrt functions. You can refer to this

def prime(num):
if num==1:
    return False
else:
    for i in range(2,num):
        if num%i==0:
            return False
return True

print(prime(17))

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