前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SPOJ PRIME1 - Prime Generator(线性筛)

SPOJ PRIME1 - Prime Generator(线性筛)

作者头像
attack
发布2018-08-01 11:20:08
1700
发布2018-08-01 11:20:08
举报
文章被收录于专栏:数据结构与算法

Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

Input

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.

Output

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.

Example

代码语言:javascript
复制
Input:
2
1 10
3 5

Output:
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.

这网站没法搜题??!!

这也太狗血了吧qwq。。。

算了说题,,

首先直接上线性筛是不行的。

但是考虑询问的$l,r$很小,所以我们可以依次枚举。

有一个非常重要的性质:对于一个合数$x$,其除$1$外最小的质因子$<= \sqrt{x}$,

然后每次判断只需要枚举到$sqrt(x)$就可以了。

感觉强上Miller-Rabin也行。。

代码语言:javascript
复制
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAXN = 1e6 + 10, B = 31;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int prime[MAXN], vis[MAXN], tot = 0;
void Pre() {
    for(int i = 2; i <= 1e5; i++) {
        if(!vis[i]) prime[++tot] = i;
        for(int j = 1; j <= tot && prime[j] * i <= 1e5; j++) {
            vis[i * prime[j]] = 1;
            if(!i % prime[j]) break;
        }
    }
}
int check(int x) {
    int limit = sqrt(x);
    if(x == 1) return 0;
    for(int i = 1; prime[i] <= limit; i++)
        if((x % prime[i]) == 0) return 0;
    return 1;
}
main() { 
    Pre();
    int qwq = read();
    while(qwq--) {
        int x = read(), y = read();
        for(int i = x; i <= y; i++) 
            if(check(i))
                printf("%d\n", i);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-06-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Input
  • Output
  • Example
  • Information
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档