首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我正在尝试编写一个打印质数的代码,但它将输出27和35这样的数字

我正在尝试编写一个打印质数的代码,但它将输出27和35这样的数字
EN

Stack Overflow用户
提问于 2019-05-11 03:41:38
回答 1查看 86关注 0票数 1

我的代码将清楚地显示出非质数,我试图找出其中的原因。

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

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2019-05-11 04:00:41

看一看:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56083915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档