Lesson 10 of 15

Prime Counting Function

The Prime Counting Function

The prime counting function π(x)\pi(x) counts the number of primes less than or equal to xx:

π(x)=#{px:p is prime}\pi(x) = \#\{p \leq x : p \text{ is prime}\}

For example: π(10)=4\pi(10) = 4 (the primes 2, 3, 5, 7), π(100)=25\pi(100) = 25.

Prime Number Theorem

The Prime Number Theorem (proved independently by Hadamard and de la Vallée Poussin in 1896) gives the asymptotic behavior:

π(x)xlnx\pi(x) \sim \frac{x}{\ln x}

A better approximation is:

π(x)xlnx1\pi(x) \approx \frac{x}{\ln x - 1}

This approximation is accurate to within a few percent for moderate values of xx.

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 π(n)\pi(n) in O(nloglogn)O(n \log \log n) 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

nnπ(n)\pi(n) exactn/(lnn1)\approx n/(\ln n - 1)Error
1002528+12%
1000168169+0.6%
1000012291218−0.9%

Your Task

Implement:

  • prime_pi(n) — exact count using the sieve
  • prime_pi_approx(n) — approximation int(round(n/(lnn1),0))\text{int}(\text{round}(n / (\ln n - 1), 0))
Python runtime loading...
Loading...
Click "Run" to execute your code.