首页 > 解决方案 > 我试图制作一个打印素数的代码,但它会吐出诸如 27 和 35 之类的数字

问题描述

我的代码会清楚地吐出非素数,我试图找出原因

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

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

标签: python

解决方案


看一看:

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

推荐阅读