素数筛,用普通的筛法肯定是会超时的,所以用欧拉筛,也就是在函数里多加了一个 if(i % prime[j] == 0) break;
#include<cstdio> #include<algorithm> #include<iostream> #include<cmath> #include<cstring> using namespace std; int prime[100000005]; bool mark[100000005]; int Prime(int n) { int sum = 0; for(int i = 2;i <= n;i++) { if(!mark[i]) prime[sum++] = i; for(int j = 0;j < sum && prime[j] * i <= n;j++) { mark[i * prime[j]] = 1; if(i % prime[j] == 0) break; } } return sum; } int main() { int n; scanf("%d", &n); printf("%d",Prime(n)); return 0; }