求 n 以内的素数和以及素数个数
复杂度:(O(n^{frac{3}{4}}))
// Created by CAD
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll check(ll v,ll n,ll ndr,ll nv) {
return v>=ndr?(n/v-1):(nv-v);
}
// n以内的素数个数
ll prime_num(ll n) {
ll r=sqrt(n);
ll ndr=n/r;
ll nv=r+ndr-1;
vector<ll> S(nv+1),V(nv+1);
for(ll i=0;i<r;i++) V[i]=n/(i+1);
for(ll i=r;i<nv;i++) V[i]=V[i-1]-1;
for(ll i=0;i<nv;i++) S[i] = V[i] - 1;
for(ll p=2; p<=r; p++)
if(S[nv-p] > S[nv-p+1]) {
ll sp=S[nv-p+1];
ll p2=p*p;
for(ll i=0;i<nv;i++) {
if(V[i]>=p2)
S[i]-=1ll*(S[check(V[i]/p,n,ndr,nv)]-sp);
else break;
}
}
return S[0];
}
// n以内所有质数和
ll prime_sum(ll n) {
ll r=sqrt(n);
ll ndr=n/r;
ll nv=r+ndr-1;
vector<ll> S(nv+1),V(nv+1);
for(ll i=0;i<r;i++) V[i]=n/(i+1);
for(ll i=r;i<nv;i++) V[i]=V[i-1]-1;
for(ll i=0;i<nv;i++) S[i] = V[i]*(V[i]+1)/2-1;
for(ll p=2;p<=r;p++)
if(S[nv-p]>S[nv-p+1]) {
ll sp = S[nv-p+1];
ll p2 = p*p;
for(ll i=0;i<nv;i++) {
if(V[i]>=p2)
S[i]-=p*(S[check(V[i]/p,n,ndr,nv)]-sp);
else break;
}
}
return S[0];
}
int main(){
}