31. Count the primes
A prime number is a whole number greater than 1 that can be divided evenly only by 1 and by itself. 2, 3, 5, 7 and 11 are prime; 4 (2 x 2) and 9 (3 x 3) are not. 0 and 1 are not prime.
Write a function count_primes(n) that takes a whole number n and returns how many prime numbers there are from 2
up to and including n. If n is less than 2, there are none: return 0.
It must be fast. n goes up to 200,000, and checking every possible divisor of every number takes far too long.
Your code has to answer count_primes(200000) in about a second.
Example 1
n = 104Example 2
n = 136Example 3
n = 10Constraints
nis a whole number from 0 to 200,000.
Submit also runs 5 more tests you can't see.
Practises For Loops (lesson 13).
- Testing every number for divisors is too slow for
n = 200000. Instead, cross out the numbers that can't be prime: the Sieve of Eratosthenes. - Handle
n < 2first: there are no primes then. Otherwise makeis_prime = [True] * (n + 1), where indexksays whetherkis prime, and set indexes 0 and 1 toFalse. - For each
kfrom 2 whilek * k <= n, ifis_prime[k]is stillTrue, set its multiples fromk * kon toFalsewithrange(k * k, n + 1, k); smaller multiples were crossed out by smaller primes. Thensum(is_prime)counts theTruevalues.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def count_primes(n):
"""Count the primes from 2 up to and including n.
n: int, from 0 to 200,000
Returns: int, how many prime numbers are <= n
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.