牛客网PAT练习场-数素数
题解:就是一道素数筛选法
题目地址:https://www.nowcoder.com/questionTerminal/e0fb49acb75f47e8b6fa2077d9071799
1 /** 2 * Copyright(c) 3 * All rights reserved. 4 * Author : Ycute 5 * Date : 2019-10-29-19.45.37 6 * Description : 筛选法求素数个数 7 */ 8 #include<iostream> 9 #include<cstdio> 10 #include<cmath> 11 #include<cstring> 12 #include<algorithm> 13 using namespace std; 14 15 //判断该数是否为素数; 16 bool f(int in){ 17 for(int i=2;i<=sqrt(in);++i){ 18 if(in%i==0)return false; 19 } 20 return true; 21 } 22 bool flag[200005]={0};//标记数组 23 int main(){ 24 flag[1]=1; 25 int a,b; 26 scanf("%d %d",&a,&b); 27 for(int i=2;i<200005;++i){ 28 if(flag[i]) continue; 29 if(i==2||f(i)){} 30 else{ 31 flag[i]=1; 32 } 33 int t=2; 34 while(t*i<=b){ 35 flag[t*i]=1; 36 ++t; 37 } 38 } 39 int num=1; 40 int i=0; 41 while(num<a){ 42 if(!flag[++i]) ++num; 43 } 44 int tt=0;//以10来循环 45 while(num<=b){ 46 if(!flag[++i]){ 47 if(tt==9||num==b)printf("%d\n",i); 48 else printf("%d ",i); 49 ++num; 50 tt=(tt+1)%10; 51 } 52 } 53 return 0; 54 }