以下代码或解决方案是什么意思

时间:2020-03-16 14:40:13

标签: python math boolean

我在网上搜索答案,然后设法获得以下代码来查找下一个素数。我了解代码第1部分中的数学部分,其中定义了测试函数是否为质数的函数。

import math

def isPrime(num):
    if num == 1:
        return False
    square_root = int(math.sqrt(num))
    for i in range(2, square_root + 1):
        if num % i == 0:
            return False
    return True


def nextPrime(currentPrime):
    flag = False#flag variable as a start, as false. Becomes a boonlean variable. #
    while flag == 0: #what the point of doing that?
        if currentPrime == 2: ##i guess the reason for doing that is because this is the first prime number
            currentPrime +=  1 ##so next prime number would essentially be 3, the only prime number sequence that is in the sequence, thus it is hard coded
        else:
            currentPrime +=  2  #whats the point of this?
        flag = isPrime(currentPrime) ##this as well
    return currentPrime ##i dont get it.

nextPrime(11)

1 个答案:

答案 0 :(得分:1)

这是一些质数

2、3、5、7、11、13、17、19、23、29、31、37、41、43、47、53、59、61、67、71、73、79、83、89 ,97、101、103、107、109、113、127、131、137、139、149、151、157、163、167、173、179、181、191、193、197、199

可以看到,除了2以外,它们都是奇数,除2和3外,它们都是非序数。

因此,您对currentPrime += 2的提问遵循的原则是,例如,如果给定11,则else块将增加2,因为它不会有一个可能为奇数的相邻数字。如果它是2,则它可以增加1,因为它可以具有相邻的质数3。但是此解决方案有问题,请参见下面的示例。

当您传递11作为输入时,此块将在第一次运行时执行

        else:
            currentPrime +=  2  #whats the point of this?
        flag = isPrime(currentPrime) ##this as well
    return currentPrime ##i dont get it.

并将标志变量设置为true,因为13是质数。然后返回该值。 flag变量仅用于检查数字是否为质数。

在以下情况下将无法使用

如果您通过了12,该怎么办?这将导致无限循环错误,因为相同的else块将增加2,这意味着它是偶数,因此可以整除。

要解决此问题,请改为将else块改为增加b 1

        else:
            currentPrime +=  1

您还应该考虑使用vizualizer理解代码的执行,请参见here