Start learning free

LESSON 245 OF 292 · HELPER FUNCTIONS

Count the Primes in Swift: A Helper Function

Practice Read the full explanation

Given an array 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

    SWIFT · HELPER FUNCTIONS

    Count Primes in Swift, explained

    Problem overview

    Given an array of integers nums, countPrimes returns how many of them are prime. A prime is greater than 1 and divisible only by 1 and itself: 2, 3, 5, 7, 11 and so on. The numbers 0 and 1 are not prime. A number that appears several times counts every time.

    The work is split between two methods. The helper isPrime answers one question about one number, and countPrimes asks it about every element. For [2, 3, 4, 5, 6] the answer is 3, because 2, 3 and 5 are prime while 4 and 6 are not. For [0, 1, 9] it is 0, and for [7, 10, 7] it is 2, since the prime 7 counts twice.

    Approach

    To test one number n, look for a divisor between 2 and n - 1. If any number in that range divides n evenly, n is not prime, and the search can stop at once. If the whole range is checked without a hit, n is prime. Numbers below 2 are rejected before the search, because no prime is smaller than 2.

    Counting is the usual pattern: a counter starts at 0, a loop visits each number, and the counter goes up whenever the helper says true. Splitting the work this way means each method has one loop and one job. The helper's loop runs again for each number, but countPrimes never needs to know how primality is tested.

    How the helper decides

    For 9 the loop tries d = 2, where 9 % 2 is 1, then d = 3, where 9 % 3 is 0, so the function returns false and never tries 4 to 8. For 7 the loop tries 2, 3, 4, 5 and 6, finds no remainder of 0, leaves the loop and returns true. For 2 there is nothing to try at all, and the answer is true straight away. The early return is what keeps composite numbers cheap: most of them are rejected within the first few values of d.

    Notice that countPrimes contains no divisibility logic. It only decides what to do with each answer, which keeps both methods short enough to read at a glance.

    Step by step

    1. Reject numbers below 2. If n < 2, return false.
    2. Loop over the candidate divisors. d goes over 2..<n, which covers 2 up to n - 1.
    3. Test each one. If n % d == 0, d divides n, so return false immediately. This also ends the loop.
    4. Return true after the loop. No divisor was found.
    5. In countPrimes, create count with var, starting at 0.
    6. Loop over nums. The loop variable is num, and repeated numbers are visited repeatedly.
    7. Count the primes. If isPrime(num), add 1 with count += 1. The helper already returns a Bool, so the call goes straight into the if.
    8. Return count after the loop. Returning inside the loop would stop after the first number.

    The solution in Swift

    class Solution {
        func isPrime(_ n: Int) -> Bool {
            if n < 2 {
                return false
            }
            for d in 2..<n {
                if n % d == 0 {
                    return false
                }
            }
            return true
        }
    
        func countPrimes(_ nums: [Int]) -> Int {
            var count = 0
            for num in nums {
                if isPrime(num) {
                    count += 1
                }
            }
            return count
        }
    }
    

    Swift details worth knowing:

    • The guard on n < 2 protects the range. A range 2..<n with n below 2 is invalid, and creating one crashes the program at run time. After the guard, the smallest n is 2, and 2..<2 is a valid empty range, so isPrime(2) skips the loop and returns true.
    • ..< excludes the upper bound. 2..<n never includes n itself, which is what the check needs: every number divides itself.
    • % is the remainder operator. n % d == 0 means d divides n evenly.
    • Calling a sibling method needs only its name, isPrime(num), and the underscores in the signature mean no argument labels.

    Complexity

    For a single number n, the helper does at most n - 2 remainder checks, so it is O(n). A composite number usually stops early, at its smallest divisor, while a prime runs the loop to the end. For an array of k numbers with values up to M, countPrimes costs O(k * M) in the worst case. It uses O(1) extra space. Stopping the divisor search at the square root of n would be much faster, since a divisor above the square root always has a partner below it, but for the lesson's limits the plain loop is enough.

    For reference, here is that faster test as a free function. It uses a while loop that stops once d * d passes n:

    func isPrimeFast(_ n: Int) -> Bool {
        if n < 2 {
            return false
        }
        var d = 2
        while d * d <= n {
            if n % d == 0 {
                return false
            }
            d += 1
        }
        return true
    }
    

    For the inputs [0, 1, 2, 3, 4, 9, 97, 100000, 99991] it returns [false, false, true, true, false, false, true, false, true].

    Edge cases and common mistakes

    • 0 and 1. They are not prime, and the guard handles them before the range is created.
    • 2. The only even prime. The loop is empty, so it returns true.
    • Repeated numbers. [7, 10, 7] gives 2: each appearance counts, so do not collapse the array into a set.
    • Starting the loop at 1. Every number is divisible by 1, so isPrime would answer false for every input.
    • Including n in the range. Writing 2...n would find n % n == 0 and reject every number.

    Testing

    • [2, 3, 4, 5, 6] gives 3.
    • [0, 1, 9] gives 0.
    • [7, 10, 7] gives 2.
    • isPrime(97) is true, isPrime(2) is true, isPrime(1) is false and isPrime(100000) is false.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free