简体   繁体   English

python代码给出错误的输出

[英]python code giving wrong output

I have written the below code in python to print out prime numbers but its giving output like: 我已经在python中编写了以下代码来打印质数,但其输出如下:

3,5,7,**9**,11,13,**15**,17,19,**21**,23,25............99

below is the code: 下面是代码:

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

def primes(n = 1):
    while(True):
        if isprime(n): yield n
        n += 1
for n in primes():
    if n > 100: break
    print(n)

You are returning True after the number fails to be divisible by one number. 该数字无法被一个数字整除后,您将返回True You need to return true after you have checked all the numbers. 检查所有数字后,您需要返回true。 Instead, you should write 相反,您应该写

def isprime(n):
    if n == 1:
        return False
    for x in range(2, n):
        if n % x == 0:
            return False

    return True

One other note: if you are testing for prime numbers, you only need to test up to the square root of the number . 另一注:如果要测试质数,则只需要测试数字的平方根即可 If the number is not divisible by any numbers less than its square root, then it is also is not divisible by any that are greater and thus must be prime. 如果该数字不能被除其平方根以外的任何数字整除,那么它也不能被任何大于其平方根的数字整除,因此必须为质数。 This will help make your code more efficient. 这将有助于使您的代码更高效。

Your isprime function says: 您的isprime函数说:

for x in range(2, n):
    if n % x == 0:
        return False
    else:
        return True

This means that on the first iteration (when x==2 ), if n%x is not zero, it will return True. 这意味着在第一次迭代中 (当x==2 ),如果n%x不为零,它将返回True。 So it will return True for any odd number (above 1, which you skipped). 因此,对于任何奇数(您已跳过的1以上),它将返回True。

Instead, you want to return True if none of the numbers in the loop were factors. 相反,如果循环中的数字都不是因数,则您想返回True。

for x in range(2, n):
    if n % x == 0:
        return False
# the loop finished without returning false, so none of the numbers was a factor
return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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