【手撕】高效判断素数
#include<iostream> #include<vector> using namespace std; // 判断素数的代码 void countPrimes(vector<int>&res,int n) { vector<bool> rec(n, true); for (int i = 2; i*i < n; i++) { if (rec[i]) { for (int j = i * i; j < n; j += i) { rec[j] = false; } } } for (int m = 2; m < n; m++) { if (rec[m]) res.push_back(m); } } int main() { vector<int> res; countPrimes(res, 100); for (auto num : res) { cout << num << endl; } return 0; }