Skip to content

Commit b0c79d7

Browse files
committed
Made some speed improvements
1 parent cea895c commit b0c79d7

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

math/prime_count.cpp

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,28 +43,33 @@ vector<int> sieve(int n) {
4343

4444
// at least sqrt(n) for pi(n)
4545
// bigger values may be faster
46-
int const sqrt_limit = isqrt(1e12) + 1;
46+
// for values up to 1e12 the fastest is around 1e8
47+
// for values up to 1e11 the fastest is around 3e7
48+
int const sqrt_limit = 30000000;
4749

4850
auto primes = sieve(sqrt_limit);
4951

50-
using ii = pair<ll, int>;
52+
using ii = pair<ll, ll>;
5153

52-
map<ii, ll> phi_cache;
54+
// at least pi(sqrt(sqrt(n)))
55+
unordered_map<ll, ll> phi_cache[200];
5356

5457
ll phi(ll x, int a) {
55-
if (phi_cache.count({x, a})) return phi_cache[{x, a}];
56-
5758
if (a == 1) {
5859
return (x+1)/2;
5960
}
6061

62+
if (phi_cache[a].count(x)) {
63+
return phi_cache[a][x];
64+
}
65+
6166
ll res = phi(x, a-1) - phi(x / primes[a-1], a-1);
62-
phi_cache[{x, a}] = res;
67+
phi_cache[a][x] = res;
6368

6469
return res;
6570
}
6671

67-
map<ll, ll> pi_cache;
72+
unordered_map<ll, ll> pi_cache;
6873

6974
ll pi(ll x) {
7075
if (pi_cache.count(x)) return pi_cache[x];
@@ -81,7 +86,7 @@ ll pi(ll x) {
8186

8287
for (ll i = a+1; i <= b; i++) {
8388
ll w = x / primes[i-1];
84-
ll b_i = pi(sqrt(w));
89+
ll b_i = pi(isqrt(w));
8590
res -= pi(w);
8691

8792
if (i <= c) {
@@ -94,6 +99,7 @@ ll pi(ll x) {
9499
pi_cache[x] = res;
95100
return res;
96101
}
102+
97103
int main() {
98104
ll n;
99105
cin >> n;

0 commit comments

Comments
 (0)