Start learning free

LESSON 244 OF 285 · HELPER FUNCTIONS

Count Primes in Go: An isPrime Helper and a Loop

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

    GO · HELPER FUNCTIONS

    Count Primes in Go, explained

    Problem overview

    Given a slice of integers nums, return how many of them are prime. A prime is greater than 1 and divisible only by 1 and itself, so 2, 3, 5, 7, 11 and 13 are prime while 0 and 1 are not. A number that appears several times counts each time.

    The work is split in two. The helper isPrime answers "is this one number prime?" with a bool. The graded function countPrimes visits every number and counts the ones the helper approves.

    For [2, 3, 4, 5, 6] the answer is 3 (2, 3 and 5). For [0, 1, 9] it is 0, since 9 = 3 × 3. For [7, 10, 7] it is 2, because 7 is prime and counted twice.

    Approach: test one number, then count

    To test one number n, rule out everything below 2 first. Then look for a divisor: try every d from 2 up to n - 1. A single divisor proves that n is not prime, so the function can return false at once. If the loop ends without finding one, n is prime.

    Counting is the usual pattern: a counter starts at 0, a loop visits each number, and the counter goes up when the helper says true. Splitting the work this way means each function has one job and one loop.

    Step by step

    1. Return false when n < 2. This handles 0 and 1.
    2. Write a loop with d := 2; d < n; d++. Every possible divisor from 2 to n - 1 gets a turn.
    3. Inside it, return false when n % d == 0. The remainder is zero exactly when d divides n evenly.
    4. Return true after the loop. No divisor was found.
    5. In countPrimes, create count with :=, starting at 0.
    6. Loop over nums with range, keeping the value in num and dropping the index with _.
    7. Call the helper in the if: if isPrime(num), then count++. The call already gives true or false, so no comparison is needed.
    8. Return count after the loop, so every number is checked first.

    The solution in Go

    func isPrime(n int) bool {
        if n < 2 {
            return false
        }
        for d := 2; d < n; d++ {
            if n % d == 0 {
                return false
            }
        }
        return true
    }
    
    func countPrimes(nums []int) int {
        count := 0
        for _, num := range nums {
            if isPrime(num) {
                count++
            }
        }
        return count
    }
    

    Go details:

    • % is the remainder operator. 9 % 3 is 0, and 9 % 2 is 1.
    • count++ is a statement, not an expression. It adds 1 to count, but you can't write x := count++ in Go.
    • An if takes a bool directly. Go has no "truthy" values, so the condition has to be a real boolean such as the result of isPrime(num).
    • Loop variables stay local. d exists only inside its for, and the loop in countPrimes doesn't interfere with the helper's loop.

    Following the helper through two numbers

    For n = 9 the loop tries d = 2 and gets the remainder 1, so it moves on. With d = 3 the remainder is 0, so the function returns false without trying 4 to 8.

    For n = 7 the remainders for d = 2, 3, 4, 5, 6 are 1, 1, 3, 2 and 1. None is zero, the loop ends, and the function returns true.

    That difference in behaviour is the point of the early return false: a composite number is rejected as soon as its smallest divisor is found, while a prime has to survive every test before it is accepted. Only the final return true, placed after the loop, can say "prime", because only then has every divisor been ruled out.

    Where the work happens

    Only isPrime has the inner loop over divisors. countPrimes has one loop over the numbers and calls the helper once per element, so the helper's loop starts again for every number, including repeats. A number that appears three times is tested three times and counted three times. Keeping the two loops in separate functions is what keeps each one short enough to read at a glance.

    Edge cases and common mistakes

    • 0, 1 and 2. isPrime(0) and isPrime(1) are false. For 2 the loop starts at d = 2, and 2 < 2 is false, so it never runs and the function returns true. Without the n < 2 check, 0 and 1 would also fall through to true.
    • Counting the divisor as the test. Starting the loop at 1 would find that every n divides by 1 and report no primes at all. Starting at 2 avoids that, and stopping before n avoids dividing by itself.
    • Counting distinct primes. The lesson counts every appearance, so no set is needed: [7, 10, 7] gives 2.
    • Returning inside the loop. Returning count in the first turn would stop after one number.
    • Speed. For a prime, the helper tries every d up to n - 1. That is fine for values up to 100000, but a divisor pair always has one member no larger than the square root of n, so the loop condition d * d <= n would be enough. Checking every n from 0 to 100000 with both versions gives identical answers, and 9592 of those numbers are prime. The lesson keeps the simpler loop, which is easier to reason about.

    Testing

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