Jump to content

Legendre prime counting function: Difference between revisions

No edit summary
Line 310:
5761455
50847534</pre>
 
=={{header|Nim}}==
The program runs in 2.2 seconds on our laptop. Using int32 instead of naturals (64 bits on our 64 bits computer) saves 0.3 second. Using an integer rather than a tuple as key (for instance <code>x shl 32 or a</code>) saves 0.4 second.
<lang Nim>import math, strutils, sugar, tables
 
const
N = 1_000_000_000
S = sqrt(N.toFloat).int
 
var composite: array[3..S, bool]
for n in countup(3, S, 2):
if n * n > S: break
if not composite[n]:
for k in countup(n * n, S, 2 * n):
composite[k] = true
 
# Prime list. Add a dummy zero to start at index 1.
let primes = @[0, 2] & collect(newSeq, for n in countup(3, S, 2): (if not composite[n]: n))
 
var cache: Table[(Natural, Natural), Natural]
 
proc phi(x, a: Natural): Natural =
if a == 0: return x
let pair = (x, a)
if pair in cache: return cache[pair]
result = phi(x, a - 1) - phi(x div primes[a], a - 1)
cache[pair] = result
 
proc π(n: Natural): Natural =
if n <= 2: return 0
let a = π(sqrt(n.toFloat).Natural)
result = phi(n, a) + a - 1
 
var n = 1
for i in 0..9:
echo "π(10^$1) = $2".format(i, π(n))
n *= 10</lang>
 
{{out}}
<pre>π(10^0) = 0
π(10^1) = 4
π(10^2) = 25
π(10^3) = 168
π(10^4) = 1229
π(10^5) = 9592
π(10^6) = 78498
π(10^7) = 664579
π(10^8) = 5761455
π(10^9) = 50847534</pre>
 
=={{header|Picat}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.