100 XP

31. Count the primes

Advanced math loops

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

Inputn = 10
Output4
ExplanationThe primes up to 10 are 2, 3, 5 and 7.

Example 2

Inputn = 13
Output6
Explanation2, 3, 5, 7, 11 and 13: n counts too.

Example 3

Inputn = 1
Output0
ExplanationThere are no primes below 2.

Constraints

  • n is a whole number from 0 to 200,000.

Submit also runs 5 more tests you can't see.

Practises For Loops (lesson 13).

Code
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