主要参考 http://www.zhihu.com/question/29580448/answer/45218281
https://projecteuler.net/thread=10;page=5 Lucy_Hedgehog 的代码
如果不用map,自己写hash函数会更快
// 计算 Π(n-1)class Solution { public: int countPrimes(int n) { n--; if(n<=1) return 0; int r = int(sqrt(n)); map<int ,int> hmp; for(int i = 1;i<=r;i++) hmp[n/i] = n/i - 1; for(int i = n/r -1;i>0;i--) hmp[i] = i - 1; for(int p = 2;p<=r;p++){ if(hmp[p]>hmp[p-1]){ int sp = hmp[p-1]; int p2 = p*p; for(int i = 1;i<=r;i++){ int t = n/i; if(t<p2) break; hmp[t] -= hmp[t/p] - sp; } for(int i = n/r -1;i>0;i--){ if(i<p2) break; hmp[i] -= hmp[i/p] - sp; } } } return hmp[n]; } };
//计算 2....n之间的素数和long long P10(long long n){ long long r = long long(sqrt(n)); hash_map<long long,long long> hmp; for(long long i = 1;i<=r;i++){ long long t = n/i; hmp[t] = t*(t+1)/2 - 1; } for(long long i = n/r -1;i>0;i--){ long long t = i; hmp[t] = t*(t+1)/2 - 1; } for(long long p = 2;p<=r;p++){ if(hmp[p]>hmp[p-1]){ long long sp = hmp[p-1]; long long p2 = p*p; for(long long i = 1;i<=r;i++){ long long t = n/i; if(t<p2) break; hmp[t] -= p*(hmp[t/p] - sp); } for(long long i = n/r -1;i>0;i--){ long long t = i; if(t<p2) break; hmp[t] -= p*(hmp[t/p] - sp); } } } return hmp[n]; }
时间: 2024-11-05 14:58:35