python - 我试图编写一个打印素数的代码,但它会输出诸如 27 和 35 之类的数字

标签 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

最佳答案

看一下:

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

关于python - 我试图编写一个打印素数的代码,但它会输出诸如 27 和 35 之类的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083915/

相关文章:

python - PySide/PyQt QMainWindow 如何关闭 QDockWidget?

python : How to "merge" two class

python - 在 HTML 文件中使用 pylab 创建的应用程序(使用 Django 创建)中使用图表

python在类中的dll回调函数中访问self

python - 将 pandas 列值替换为字典值

python - 自定义 virtualenv `activate` 脚本

python - 在 **kwargs 中使用 OrderedDict

jquery - 为什么 json.dumps() 在使用变量时会抛出 500 内部服务器错误?

python - 检查 Python 包是否需要 Visual Studio 构建工具

python - 通过 Nose 测试与多个实体组运行事务时出错