2469 - 【数组】筛法求素数(例题)
例5.7 用筛法求出100以内的全部素数,并按每行五个数显示。
Input
无输入。
Output
多行,从小到大输出素数,每行五个素数,素数之间用一个空格分隔,每行最后不能有空格。
Examples
Input
no input needed
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
Solution C++
#include<iostream> #include<math.h> #include<cstring> using namespace std; int n=100; int t; bool a[101]; int main() { memset(a,1,sizeof(a)) , a[1]=0; for (int i=2; i<=sqrt(n); ++i) if (a[i]) for (int j=2; j<=n/i; ++j) a[i*j]=0; t=0; for (int i=2; i<n+1; ++i) if (a[i]) { t++; if (t%5==0) cout<<i<<endl; else cout<<i<<" "; } return 0; }