1. 程式人生 > >HDU 5901 1-n中素數個數

HDU 5901 1-n中素數個數

Count primes

Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)


Problem Description Easy question! Calculate how many primes between [1...n]!
Input Each line contain one integer n(1 <= n <= 1e11).Process to end of file.
Output For each case, output the number of primes in interval [1...n]
Sample Input 2 3 10
Sample Output 1 2 4題意:1-n中素數個數題解:別人的程式碼,看不懂,拉過來當模板儲存起來吧。。。
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll f[340000],g[340000],n;
void init(){
    ll i,j,m;
    for(m=1;m*m<=n;++m)f[m]=n/m-1;
    for(i=1;i<=m;++i)g[i]=i-1;
    for(i=2;i<=m;++i){
        if(g[i]==g[i-1])continue;
        for(j=1;j<=min(m-1,n/i/i);++j){
            if(i*j<m)f[j]-=f[i*j]-g[i-1];
            else f[j]-=g[n/i/j]-g[i-1];
        }
        for(j=m;j>=i*i;--j)g[j]-=g[j/i]-g[i-1];
    }
}
int main(){
    while(scanf("%I64d",&n)!=EOF){
        init();
        cout<<f[1]<<endl;
    }
    return 0;
}