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

Python求1-100素数:仅改第4行使循环迭代达245次求助

修改素数判断函数以达到指定循环迭代次数

我是一名刚接触Python的学生,写了一个计算1-100之间素数的程序,当前循环迭代次数是139次。为了拿到更高分数,要求仅修改is_prime函数的第4行,让程序的循环迭代次数恰好为245次。下面是我的初始代码和修改后的代码,希望能得到帮助,我很享受学习Python的过程!

初始代码

def is_prime(num):
    if num < 2:
        return False
    the_end = num
    for i in range(2, the_end):
        if num % i == 0:
            return False
        return True
    
print("The 25 numbers between 1 and 100:")
count = 0
for num in range(1, 101):
    if is_prime(num):
        count = count + 1
        print(count, num)

修改后的代码

def is_prime(num):
    if num < 2:
        return False
    the_end = int(num ** 0.5) + 1
    for i in range(2, the_end):
        if num % i == 0:
            return False
    return True

print("The 25 prime numbers between 1 and 100:")
count = 0
for num in range(1, 101):
    if is_prime(num):
        count = count + 1
        print(count, num)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:05:53