This is a very similar question to Most efficient algorithm for nth prime, deterministic and probabilistic?
There are quite a few ways, depending on how much you want to optimize, what your expected range is, and how much code you want to write. If you don't have very large inputs, you can compute (easily) an upper bound, then use a segmented sieve counting as you go. For the SPOJ problem you give, it looks tight on time to me (sieve and count to 2.3e10 in under 3 seconds). Even primesieve would be very pressed for time. Some clever tables could reduce the work a lot with very little source, making it quite possible (since your range really isn't all that large).
gammatester gives a good answer, but as the answers on the other question note, and hardmath points out in his comment, we can improve. Get a good estimate (e.g. $R^{-1}$), perform a fast prime count algorithm, then sieve segments and count forward or backward as needed. In my code I was lazy and wrote a fast sieve forward count but just a prev_prime
loop going backwards. So I bias my estimate a little under. I use ${\rm Li}^{-1}(n)+{\rm Li}^{-1}(\sqrt{n})/4$ which gets very close but is rarely over, and not by much when it is. If you were symmetrical then either $/2$ in the latter formula or go with inverse Riemann R.
At 5000 bytes of source, this also is a bit constrained as we're not going to write LMO. For this size of n, the simpler methods of Legendre, Meissel, or Lehmer with a simple phi function ought to work just fine. Riesel (1994) should have everything needed, and TOeS's paper referenced by gammatester has a simple Legendre implementation. Note Table II is a rudimentary Legendre (1830) algorithm, which is slower than Meissel or Lehmer and much slower than the extended LMO the paper is really about; implementing the latter is not easy and his paper is a long tough slog to working code. It may be good enough for this problem however, and there are lots of not-complicated optimizations possible for phi(x,a).
Addendum. For the very practical, some methods and programs:
- Go to Wolfram Alpha, type
Prime[n]
where n is your number.
- https://primes.utm.edu/nthprime/ Uses very dense tables followed by sieving with primesieve.
- http://sti15.com/nt/nthprime.cgi an example page using my code on a slow web server. Limited to 10^12 to be kind to other clients. It's just a 1990's web wrapper around
perl -E 'use ntheory ":all"; say nth_prime(...)'
- https://github.com/kimwalisch/primecount Kim Walisch's excellent primecount project. Fastest open source implementation on multiple cores, and works on >64-bit inputs as well.
- https://github.com/danaj/Math-Prime-Util my C code inside a Perl module, though most of it can be compiled as standalone C. A little faster than primecount on a single thread.