Start learning free

LESSON 240 OF 287 · HELPER FUNCTIONS

Count Primes in Python: A Helper and a Counter

Practice Read the full explanation

Given a list of integers nums, return how many of them are prime numbers.

A prime number is greater than 1 and can be divided evenly only by 1 and by itself: 2, 3, 5, 7, 11, 13 and so on. 0 and 1 are not prime. If a number appears more than once, each appearance counts.

The work is split between two functions. The first one is a helper: it gets one number and returns True if it is prime, False if it is not. The second one, the function that is graded, goes over the numbers and counts the ones the helper says are prime.

 

Example 1:

Input: nums = [2, 3, 4, 5, 6]
Output: 3
Explanation: 2, 3 and 5 are prime. 4 = 2 × 2 and 6 = 2 × 3 are not.

Example 2:

Input: nums = [0, 1, 9]
Output: 0
Explanation: 0 and 1 are never prime, and 9 = 3 × 3.

Example 3:

Input: nums = [7, 10, 7]
Output: 2
Explanation: 7 is prime and appears twice, so it counts twice. 10 = 2 × 5 is not prime.

 

Constraints:

  • nums has at least one number.
  • Every number is an integer from 0 to 100000.
STEP 1 OF 8
    Ctrl + Enter to check

    PYTHON · HELPER FUNCTIONS

    Count Primes in Python, explained

    Problem overview

    Given a list of integers nums, return how many of them are prime. A prime is greater than 1 and divisible only by 1 and itself. 0 and 1 are not prime, and a number that appears twice counts twice.

    The work is split in two methods. isPrime is a helper that takes one number and returns True or False. countPrimes loops over the list and counts the numbers the helper accepts. For [2, 3, 4, 5, 6] the answer is 3, for [0, 1, 9] it is 0, and for [7, 10, 7] it is 2, because the prime 7 appears twice.

    Approach

    To show that n is not prime, one divisor between 2 and n - 1 is enough. To show that it is prime, no such divisor may exist. So the helper tries each candidate d in turn and gives up with False as soon as one divides n evenly. If the loop finishes without a hit, the answer is True.

    Numbers below 2 need a special case first: the loop over range(2, n) would be empty for 0 and 1, and the helper would wrongly report them as prime.

    The counting method then uses the helper like any other yes/no question: one loop, one counter, one if.

    Step by step

    1. In isPrime, return False if n < 2. No prime is smaller than 2.
    2. Loop d over range(2, n), the numbers from 2 to n - 1.
    3. If n % d == 0, return False. The remainder is 0 when d divides n evenly. One divisor settles the question, and return stops the loop and the function at once.
    4. Return True after the loop. No divisor was found.
    5. In countPrimes, set count = 0. Nothing has been counted yet.
    6. Loop num over nums. A repeated number is visited each time it appears, so it counts each time.
    7. If self.isPrime(num) is true, add 1 to count. The call already returns True or False, so it goes straight into the if.
    8. Return count after the loop, once every number has been checked.

    The solution in Python

    class Solution:
        def isPrime(self, n: int) -> bool:
            if n < 2:
                return False
            for d in range(2, n):
                if n % d == 0:
                    return False
            return True
    
        def countPrimes(self, nums: List[int]) -> int:
            count = 0
            for num in nums:
                if self.isPrime(num):
                    count += 1
            return count
    

    Python details:

    • range(2, n) excludes n. It yields 2 up to n - 1. For n = 2 it is empty, and for n = 3 it holds only 2, which does not divide 3. Both fall through to True, which is right.
    • % gives the remainder. For positive numbers, n % d == 0 means d divides n exactly.
    • Two loops, two functions. Each function has its own loop and its own variables. countPrimes only calls isPrime, which runs its loop again for every number.

    Tracing the helper

    For n = 9, the loop tries d = 2 (remainder 1) and d = 3 (remainder 0). At d = 3 the test n % d == 0 is true, so isPrime(9) returns False without trying 4 to 8.

    For n = 7, the remainders for d = 2 to 6 are 1, 1, 3, 2 and 1. None is 0, so the loop ends and the function returns True. A prime always runs the whole loop, while a composite number stops at its smallest divisor.

    The range is also why the edge cases work. range(2, 2) is empty and range(2, 3) holds only 2, so for n = 2 and n = 3 the loop finds no divisor and the function returns True.

    A faster divisor search

    The reference loop tests every d up to n - 1, but that is more than needed. If n has a divisor, it has one no larger than its square root. For 99991 the integer square root is 316, so about 315 tests would be enough instead of nearly 100000. The lesson's version keeps the loop simple; the square-root bound is an optimisation to try once the basic version works.

    Complexity

    For one number n, isPrime does at most about n divisions, and it does the full amount for a prime. For a list of k numbers up to 100000, the total work is at most about k * 100000 divisions. That is fine for the lesson's inputs. Faster tests stop at the square root of n, because a number with a divisor has one no larger than its square root, but the simple loop is enough here. Extra space is a few integers.

    Edge cases and common mistakes

    • 0 and 1. Without the n < 2 check, both would return True, since the loop over range(2, n) is empty. [0, 1, 9] would then count 2 instead of 0.
    • 2 is prime. It is the only even prime, and the code handles it with no special case.
    • Returning True inside the loop. Finding that d does not divide n proves nothing. Only after every d has failed is n prime.
    • Returning count inside the loop stops after the first number.
    • Duplicates. The list is not turned into a set, so [7, 10, 7] gives 2.

    Testing

    • [2, 3, 4, 5, 6] gives 3.
    • [0, 1, 9] gives 0.
    • [7, 10, 7] gives 2.
    • isPrime on 0, 1, 2, 3, 4, 9 and 97 gives False, False, True, True, False, False, True.
    • [99991] gives 1: 99991 is prime.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free