Determining if a number is prime in the above code [duplicate]

拟墨画扇 提交于 2019-12-11 18:19:05

问题


I have a simple problem: take a number and determine if it is prime. I cannot figure out why on earth the following does not work.

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

prime(21)

This returns true! I have no idea why.


回答1:


In your code you have put return True inside the for loop, so it only checks whether the number is divisible by two and if not, it returns true.

Rather use this

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

Also to improve efficiency a bit use for i in range (2, int(x/2)+1) since once you have reached x/2 no number after that can divide it anyhow.

In future try debugging your code by printing values of loop indexes where it defaults or using a debugger, it is real helpful and helps you improve as a programmer.



来源:https://stackoverflow.com/questions/54473512/determining-if-a-number-is-prime-in-the-above-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!