python - 我试图制作一个打印素数的代码,但它会吐出诸如 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
解决方案
看一看:
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
推荐阅读
- nutch - 如何在种子文件中添加 nutch1.17 新网址将 nutch 获取旧网址和新网址?
- android - 在获取保存响应时禁用 Listview 行中的按钮?
- php - PHP 联系表 GDPR 验证
- c# - 如何将 Serilog 附加到 dotnetcore 日志框架并将日志服务作为开放通用类型注入
- python - 一个比例图中的多线图
- javascript - 如何对具有相同功能的多个元素执行转换
- vim - 如何删除直到(不包括)行上的最后一个字符
- sql - 创建可变报告期:'2019 - 2020'
- python - Python:在数据框中查找特定列值总和为 0 的所有行
- c++ - 在 VS 代码中调试 C++ 时不接受终端中的用户输入