本题要求使用筛法求出1~N以内的质数。
函数接口定义:
vector sieve(int n); //函数声明, 求n以内的质数
求n以内的质数。其中 n是传入的参数。n 的值不超过10 000 000的范围; 求出的质数存入容器vector并返回。
裁判测试程序样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <iostream> #include <vector> using namespace std;
vector<int> sieve(int n);
int main(int argc, char const *argv[]) { int n; cin >> n;
vector<int> ans = sieve(n);
cout << ans.size() << endl; for (int i = 0; i < ans.size(); i++) { cout << ans[i]; if (i < ans.size() - 1)cout << " "; } cout << endl;
return 0; }
|
参考链接
答案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include<string.h> bool a[10000002]; vector<int> sieve(int n) { vector<int> temp; int cont = 0; memset(a, true, sizeof(a)); for (int i = 2; i <= n; ++i) { if (a[i]) { temp.push_back(i); } cont = temp.size(); for (int j = 0; j < cont&&temp[j]*i<=n; ++j) { a[temp[j] * i] = false; if (i % temp[j] == 0) { break; } } } return temp; }
|