我正在尝试制作一个输出质数的代码,但会吐出诸如27和35之类的数字

时间:2019-05-10 19:41:38

标签: python

我的代码将清楚地吐出非质数,并试图找出原因

当我运行代码时,它输出素数,但偶尔也会输出非素数

x = 1
a = 4
b=2
#prints 2
print(2)
#prints 3
print(3)
#whilst x is under 1000, the next section of code will run
while x < 100:
    #sets b to 2
    b = 2
    #will repeat aslong as b is less than a
    while b < a:
       #if a can be divided by b with no remainder
        if a % b == 0:
            #adds 1 to a
            a = a+1
            #if not will add one to b
        else:
            b = b+1
    print(a)
    a = a+1
    x = x+1

1 个答案:

答案 0 :(得分:1)

看看:

x = 1
a = 4
#prints 2
print(2)
#prints 3
print(3)
#whilst x is under 1000, the next section of code will run
while x < 100:
    #sets b to 2
    b = 2
    #will repeat aslong as b is less than a
    while b < a:
       #if a can be divided by b with no remainder
        if a % b == 0:
            #adds 1 to a
            a = a+1

            b = 2  # <-- Point is here!
            # When a and b are not coprimes, we have to go back
            # and look for all possible values for b again for this new value of a.

            #if not will add one to b
        else:
            b = b+1
    print(a)
    a = a+1
    x = x+1