Skip to content

Commit

Permalink
Add nth_prime_approx(n)
Browse files Browse the repository at this point in the history
  • Loading branch information
kimwalisch committed Jan 10, 2024
1 parent be93e84 commit 251abd3
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 11 deletions.
1 change: 1 addition & 0 deletions include/primecount-internal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ int64_t Li(int64_t);
int64_t Li_inverse(int64_t);
int64_t Ri(int64_t);
int64_t Ri_inverse(int64_t);
int64_t nth_prime_approx(int64_t n);

#ifdef HAVE_INT128_T
int128_t pi(int128_t x);
Expand Down
15 changes: 15 additions & 0 deletions src/RiemannR.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,21 @@ int64_t Ri_inverse(int64_t x)
return (int64_t) res;
}

/// nth_prime_approx(n) is a very accurate approximation of the nth
/// prime with |nth prime - nth_prime_approx(n)| < sqrt(nth prime).
/// Please note that nth_prime_approx(n) may be smaller or larger than
/// the actual nth prime.
///
int64_t nth_prime_approx(int64_t n)
{
// Li_inverse(n) is faster but less accurate than Ri_inverse(n).
// For small n speed is more important than accuracy.
if (n < 1e8)
return Li_inverse(n);
else
return Ri_inverse(n);
}

#ifdef HAVE_INT128_T

int128_t Li(int128_t x)
Expand Down
15 changes: 4 additions & 11 deletions src/nth_prime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,17 +98,10 @@ int64_t nth_prime(int64_t n, int threads)
if (n <= PiTable::pi_cache(PiTable::max_cached()))
return binary_search_nth_prime(n);

int64_t prime_approx;

// Li_inverse(x) is faster but less accurate than Ri_inverse(x).
// For small n speed is more important than accuracy.
if (n < 1e8)
prime_approx = Li_inverse(n);
else
prime_approx = Ri_inverse(n);

// For large n we use the prime counting function
// and the segmented sieve of Eratosthenes.
// Closely approximate the nth prime using the inverse
// Riemann R function and then count the primes up to this
// approximation using the prime counting function.
int64_t prime_approx = nth_prime_approx(n);
int64_t count_approx = pi(prime_approx, threads);
int64_t avg_prime_gap = ilog(prime_approx) + 2;
int64_t prime = -1;
Expand Down

0 comments on commit 251abd3

Please sign in to comment.