标签:end stdin mem pen void 复杂度 algo const string
埃氏筛法:从1到n遍历一遍,每找到一个素数就记录下来并把它的倍数全部筛掉。
时间复杂度:O(nlog(log (n)) )
code:
#include <iostream> #include <string> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <queue> #include <functional> #include <map> #include <set> #include <stack> #define FT(a, b) memset(a, b, sizeof(a)) #define FAT(a) memset(a, 0, sizeof(a)) using namespace std; typedef long long ll; const int M = 1e6 + 10; const int INF = 0x3f3f3f3f; int n, prime[M], cnt,vis[M]; void get_prime() { for(int i = 2;i<=n;i++) { if(!vis[i]) { prime[cnt++] = i; for(int j = 2;j<=n/i;j++) { vis[j*i] = 1; } } } } int main() { #ifdef ONLINE_JUDGE #else freopen("/home/wjy/code/c++/in.txt", "r", stdin); #endif scanf("%d", &n); FAT(vis);
cnt = 0; get_prime(); printf("%d\n", cnt); return 0; }
线性(欧拉)筛法: 把1~n内全部合数用最小质因子筛掉。
时间复杂度O(n)
代码:
#include <iostream> #include <string> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <queue> #include <functional> #include <map> #include <set> #include <stack> #define FT(a, b) memset(a, b, sizeof(a)) #define FAT(a) memset(a, 0, sizeof(a)) using namespace std; typedef long long ll; const int M = 1e6 + 10; const int INF = 0x3f3f3f3f; int n, prime[M], cnt, vis[M]; void get_prime() { for (int i = 2; i <= n; i++) { if (!vis[i]) prime[cnt++] = i; for (int j = 0; prime[j] <= n / i; j++) { vis[prime[j] * i] = 1; if (i % prime[j] == 0) break; } } } int main() { #ifdef ONLINE_JUDGE #else freopen("/home/wjy/code/c++/in.txt", "r", stdin); #endif scanf("%d", &n); FAT(vis); cnt = 0; get_prime(); printf("%d\n", cnt); return 0; }
标签:end stdin mem pen void 复杂度 algo const string
原文地址:https://www.cnblogs.com/ignorance/p/12204029.html