欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

求小于N的素数个数(N>1e9)

程序员文章站 2024-03-14 20:49:53
...
#include<bits/stdc++.h>
#define il inline
#define pb push_back
#define ms(_data,v) memset(_data,v,sizeof(_data))
#define SZ(a) int((a).size())
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f;
const int N=320005;
//il int Add(int &x,ll y) {return x=x+y>=mod?x+y-mod:x+y;}
//il int Mul(int &x,ll y) {return x=x*y>=mod?x*y%mod:x*y;}
ll phi[10005][105], p2[N], ans[N];
int len, vis[N];
void init() {
	len = 0;
	for(int i=2; i<N; i++) {
		if(!vis[i]) {
			for(int j=i+i; j<N; j+=i) vis[j]=1;
			p2[len++] = i;
			ans[i] = ans[i-1]+1;
			continue;
		}
		ans[i] = ans[i-1];
	}
	for(int i=0; i<=10000; i++) {
		phi[i][0] = (ll)i;
		for(int j=1; j<=100; j++) {
			phi[i][j] = phi[i][j-1] - phi[i/p2[j-1]][j-1];
		}
	}
}
ll solve_phi(ll m, ll n) {
	if(!n) return m;
	if(p2[n - 1] >= m) return 1;
	if(m<=10000 && n<=100) return phi[m][n];
	return solve_phi(m, n-1) - solve_phi(m/p2[n-1], n-1);
}
ll solve_p2(ll m) {
	if(m < (ll)N) return ans[m];
	ll y = (int)cbrt(m*1.0);
	ll n = ans[y];
	ll sum = solve_phi(m, n) + n -1;
	for(ll i=n; p2[i]*p2[i]<=m; i++)
		sum = sum - solve_p2(m/p2[i])+solve_p2(p2[i])-1;
	return sum;
}
int main(){
    init();
    scanf("%lld", &n);
    printf("%lld\n",solve_p2(n));
    return 0;
}