PTA乙级题目1013(python3【有一个超时】 + c++)

PTA乙级题目1013(python3【有一个超时】 + c++)

题目信息:
令 P​i表示第 i 个素数。现任给两个正整数 M≤N≤10​4,请输出 P​M到 PN的所有素数。

输入格式:
输入在一行中给出 M 和 N,其间以空格分隔。

输出格式:
输出从 PM到 P​N的所有素数,每 10 个数字占 1 行,其间以空格分隔,但行末不得有多余空格。

c++(未超时)

#include <iostream>
#include <cmath>
using namespace std;

//计算质数(常用方法)
int jisuan(int i)
{
    for(int a = 2; a <= (int)sqrt(i); a++)
    {
        if(i % a == 0)
        {
            return jisuan(i + 2);
        }
        
    }
    return (int)i;
}

int main()
{
    int a,b;
    cin>>a>>b;

    int *resultlist = new int[b];
    resultlist[0] = 1;
    resultlist[1] = 2;
    resultlist[2] = 3;

    int c = 3;

	//生成质数数组
    for(int i = 3; i <= b; i++)
    {
        resultlist[i] = jisuan(resultlist[i - 1] + 2);
    }

	//输出从a到b区间内容
    int count = 0;
    for(int i = a; i < b; i++)
    {
        if((count + 1) % 10 == 0 && count != 0)
        {
            cout<<resultlist[i]<<"\n";
            count++;
        }
        else
        {
            cout<<resultlist[i]<<" ";
            count++;
        }
        
    }
    //输出最后一个
    cout<<resultlist[b];
    // system("pause");
    return 0;
}

python3

x, y = input().strip().split()
x = int(x)
y = int(y)

# 计算质数
def jisuan(i):
    if i == 1 or i == 2:
        return i
    for a in range(3, int(pow(i + 1, 0.5)) + 1):
        if i % a == 0:
            return jisuan(i + 2)
    return i
        

a = 1
result = 0
# 运行并输出
for i in range(y + 1):
    a = jisuan(a)
    if i >= x:
        if i == y:
            print(str(a), end="")
        elif result % 10 == 0 and result != 0:
            result += 1
            print("\n" + str(a) + " ", end="")
        elif (result + 1) % 10 == 0 and result != 0:
            result += 1
            print(str(a), end="")
        else:
            result += 1
            print(str(a) + " ", end="")
    if a >= 3:
        a += 2
    else:
        a += 1

总结
运行python3时有一个超时,一样的算法换了c++就不超了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘻嘻哈哈笑呵呵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值