SP2 PRIME1 - Prime Generator,解题未遂的欧拉筛法,改用经典优化素数算法

题目来自:SPOJ
当然可以在洛谷提交:https://www.luogu.com.cn/problem/SP2
题目描述
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

输入格式
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

输出格式
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

题意翻译
求给定的两个数之间的素数

Translated by @kaiming

输入输出样例
输入

2
1 10
3 5

输出

2
3
5
7

3
5

说明/提示

Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed) Information

After cluster change, please consider PRINT as a more challenging problem.


我一开始打算直接用经典的开方判断解决,但是我看到了这些:
SP2 PRIME1 - Prime Generator,解题未遂的欧拉筛法,改用经典优化素数算法
SP2 PRIME1 - Prime Generator,解题未遂的欧拉筛法,改用经典优化素数算法
我直接放弃了这个方法,打算实践一下我的素数筛算法:
错误代码如下:

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

bool mark[1000000005];
int n, s, e;
void xxs()
{
    if (s == 1)
        s += 1;
    for (int i = 2; i <= e; i++)
    {
        if (!mark[i])
        {
            for (int j = i * i; j <= e; j += i)
                mark[j] = 1;
        }
    }
    for (int i = s; i <= e; i++)
        if (!mark[i])
            cout << i << " ";
}

int main()
{
    // for (int i = 2; i <= 1000000005; i++)
    //     mark[i] = 1;
    cin >> n;
    while (n--)
    {
        cin >> s >> e;
        memset(mark, false, sizeof(mark));
        xxs();
        cout << endl;
    }
    return 0;
}

给我报错RE,我一直没检查出来,请大佬帮忙指正。

然后我*使用了经典算法,但是——TLE了,我想看看优化优化行不行。
于是我就优化成了这样:

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
#define LL long long
LL n, s, e;
void prime()
{
    int cnt = 0, flag = 0;
    if (s == 1)
        s += 1;
    for (int i = s; i <= e; i++)
    {
        flag = 0;
        for (int j = 2; j * j <= i; j++)
        {
            if (i % j == 0)
            {
                flag = 1;
                break;
            }
        }
        if (!flag)
        {
            cout << i << " ";
        }
    }
    cout << endl;
}
int main()
{
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> s >> e;
        prime();
    }
    return 0;
}

判断的地方优化了一下,只要i%j==0,就说明i不是素数,直接跳出循环继续下一个数可以优化很多时间。除了j=1或者j=i,但这都不可能。
SP2 PRIME1 - Prime Generator,解题未遂的欧拉筛法,改用经典优化素数算法

上一篇:Mark Down学习


下一篇:P4145 上帝造题的七分钟2 / 花神游历各国