You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python质数程序优化:实现每行输出10个质数

解决方案:实现质数每行10个输出

你只需要在每次找到质数并递增count后,判断count是否是10的倍数,若是则触发换行即可。修改后的代码如下:

num = int(input("How many primes: "))
count = 0
prime = 2
while count < num:
    if all(prime % j != 0 for j in range(2, prime)):     
        print(prime, end=" ")
        count += 1
        # 每10个质数后换行
        if count % 10 == 0:
            print()
    prime += 1

代码说明

当count的值是10的整数倍时(比如第10、20...个质数),执行print()来换行,确保每行恰好输出10个质数。

如果想让每行末尾没有多余空格,可以用列表收集每10个质数后再打印,示例如下:

num = int(input("How many primes: "))
count = 0
prime = 2
current_line = []
while count < num:
    if all(prime % j != 0 for j in range(2, prime)):     
        current_line.append(str(prime))
        count += 1
        # 每10个质数打印一行并清空列表
        if count % 10 == 0:
            print(" ".join(current_line))
            current_line = []
    prime += 1
# 处理最后一行不足10个的情况
if current_line:
    print(" ".join(current_line))

这个版本会让质数间用空格分隔,每行末尾无多余空格,输出格式更规范。

内容的提问来源于stack exchange,提问作者Sodrob Sodrob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:15:41