Lesson 10 of 15
Prime Counting Function
The Prime Counting Function
The prime counting function counts the number of primes less than or equal to :
For example: (the primes 2, 3, 5, 7), .
Prime Number Theorem
The Prime Number Theorem (proved independently by Hadamard and de la Vallée Poussin in 1896) gives the asymptotic behavior:
A better approximation is:
This approximation is accurate to within a few percent for moderate values of .
import math
def prime_pi_approx(n):
if n < 2:
return 0
return int(round(n / (math.log(n) - 1), 0))
print(prime_pi_approx(100)) # 28 (exact: 25)
Exact Count with the Sieve
For the exact count, the Sieve of Eratosthenes gives in time:
def prime_pi(n):
if n < 2:
return 0
is_p = [True] * (n + 1)
is_p[0] = is_p[1] = False
for i in range(2, int(n**0.5) + 1):
if is_p[i]:
for j in range(i*i, n+1, i):
is_p[j] = False
return sum(is_p)
print(prime_pi(100)) # 25
print(prime_pi(1000)) # 168
Error of the Approximation
| exact | Error | ||
|---|---|---|---|
| 100 | 25 | 28 | +12% |
| 1000 | 168 | 169 | +0.6% |
| 10000 | 1229 | 1218 | −0.9% |
Your Task
Implement:
prime_pi(n)— exact count using the sieveprime_pi_approx(n)— approximation
Python runtime loading...
Loading...
Click "Run" to execute your code.