我的代码会清楚地输出非素数,我试图找出原因
当我运行代码时,它会输出素数,但偶尔也会输出非素数
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/