素数筛 codevs 1675 大质数 2

1675 大质数 2

 

 时间限制: 1 s
 空间限制: 1000 KB
 题目等级 : 钻石 Diamond
题解
 查看运行结果
 
 
题目描述  Description

小明因为没做作业而被数学老师罚站,之后数学老师要他回家把第n个质数找出来。

小明于是交给聪明的你。请你帮忙!【wikioi-1530】

…………………………以上为背景…………………………

老师怀疑小明仅仅是找到第n个质数,于是又叫小明把1到n以内(不包括n)的质数全部找出来。小明又找到了你……

输入描述  Input Description

一个正整数n。

(1<=n<=1000000)

输出描述  Output Description

n以内的质数,每个一行。

样例输入  Sample Input

233

样例输出  Sample Output

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229          //(不含n=233)

Euler筛法(线性筛法):
 1 #include<iostream>
 2 using namespace std;
 3 #include<cstdio>
 4 #define N 1001000
 5 #include<bitset>
 6 bitset<N>check;
 7 int prim[N],tot=0;
 8 int main()
 9 {
10     int n;
11     cin>>n;
12     check.set();
13     for(int i=2;i<n;++i)
14     {
15         if(check[i])
16         {
17             printf("%d\n",i);
18             prim[tot++]=i;
19         }
20         for(int j=0;j<tot;++j)
21         {
22             if(prim[j]*i>=n) break;
23             check[prim[j]*i]=false;
24             if(i%prim[j]==0) break;
25         }
26     }
27     
28     return 0;
29 }

埃氏筛法:

 1 /*/*这个程序在i==四万多的时候溢出了,而欧拉筛法因为有“if(i%prim[j]==0) break;
 2 ”,所以一般不会乘法溢出*/*/
 3 #include<iostream>
 4 using namespace std;
 5 #include<cstdio>
 6 #define N 1001000
 7 #include<bitset>
 8 bitset<N>check;
 9 int prim[N],tot=0;
10 int main()
11 {
12     int n;
13     cin>>n;
14     check.set();
15     for(int i=2;i<n;++i)
16     {
17         if(check[i])
18         {
19             printf("%d\n",i);
20             for(int j=i*i;j<n;j+=i)
21               check[j]=false;
22         }
23         
24     }
25     
26     return 0;
27 }

 

 

转载于:https://www.cnblogs.com/c1299401227/p/5515424.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值