HDU 5901 Count primes 2016年沈阳网络赛 (Lehmer素数计数)

Count primes

Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 155    Accepted Submission(s): 28

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
Source
Recommend
wange2014   |   We have carefully selected several similar problems for you:  5900 5899 5898 5897 5896 

题解:  Meissel-Lehmer算法。Lehmer素数计数。可以计数到1000亿!!由我来卡全场!easyquestion,说得跟真的似的。(:其实是真的,只是我太菜了....

AC代码:
//1010 by Walker

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const ll MAXN = 10000000;

ll N;
bool isp[MAXN];
int pcnt[MAXN];
vector<int> primes;
void init()
{
  	for(int i=2; i<MAXN; i++){
  		isp[i] = true;
  	}
    
  	for(int i=2; i<MAXN; i++)
 	{	
    	if(!isp[i]) continue;
    	primes.push_back(i);
    	for(int j=2*i; j<MAXN; j+=i){
    		isp[j] = false;
		}
       	
  	}
   pcnt[0] = 0;
   for(int i=1; i<MAXN; i++){
   	  pcnt[i] = pcnt[i-1] + isp[i];
   }
     
}
ll prime_count(ll lim);

ll phi(ll m, int n)
{
  	if(m <= 0) return 0;
  	if(n == 0) return m;
  	if(primes[n-1] * primes[n-1] >= m) return prime_count(m) - n + 1;
  	return phi(m, n-1) - phi(m / primes[n-1], n-1);
}

ll prime_count(ll lim)
{
  	if(lim < MAXN) return pcnt[lim];
  
  	ll m3 = 1, m2 = 1;
 	while(m3*m3*m3<=lim) m3++;
 	while(m2*m2<=lim) m2++;
  	m3--;
  	m2--;

  	ll y = m3;
  	ll n = prime_count(y);
  	ll p2 = 0;
  	for(ll p=y+1; p<=m2; p++)
	  {
  		if(isp[p]){
  			p2 += prime_count(lim / p) - prime_count(p) + 1;
		  }
      
	}
  	ll ph = phi(lim, n);
  	ll res = ph + n - 1 - p2;
  	//cout<<lim<<" y "<<y<<" n "<<n<<" p2 "<<p2<<" phi "<<ph<<endl;
  	return res;
}
int main()
{
  	init();
  	while(~scanf("%I64d",&N))
  	{
  		ll ans = prime_count(N);
  		printf("%I64d\n",ans);
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值