Start learning free

LESSON 244 OF 291 · HELPER FUNCTIONS

Count Primes in Scala: A Prime Helper and a Counting 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

    SCALA · HELPER FUNCTIONS

    Count Primes in Scala, explained

    Problem overview

    Given an array nums, countPrimes returns how many of its numbers are prime. A prime is greater than 1 and divisible evenly only by 1 and itself. 0 and 1 are not prime, and a prime that appears twice counts twice.

    The lesson splits the work into a helper, isPrime(n), which answers true or false for one number, and countPrimes, which loops over the array and counts the numbers the helper accepts. For [2, 3, 4, 5, 6] the answer is 3 (2, 3 and 5). For [0, 1, 9] it is 0. For [7, 10, 7] it is 2, because 7 counts at each appearance.

    Approach: test one number, then count

    To decide whether n is prime, look for a divisor. Any number from 2 to n - 1 that divides n evenly proves n is not prime, and one divisor is enough to stop. If the search finds none, n is prime. Numbers below 2 are rejected before the search, since no prime is smaller than 2.

    The counting method then does what any counting loop does: start at 0, visit every number, and add 1 when the helper says yes. The helper has a loop of its own, but countPrimes only calls it and doesn't need to know how it works.

    Step by step

    1. Reject numbers below 2. In isPrime, if n < 2, return false. This handles 0 and 1.
    2. Loop over the candidate divisors with for (d <- 2 until n), which covers 2 up to n - 1. For n = 2 the range is empty, so the loop body never runs.
    3. Return false on the first divisor. When n % d == 0, d divides n evenly. return leaves the loop and the method at once.
    4. Return true after the loop. If no divisor was found, the number is prime.
    5. In countPrimes, create var count = 0. It has to be a var because it changes.
    6. Loop over nums with for (num <- nums). A repeated number is visited twice, so it counts twice.
    7. Add 1 when isPrime(num) is true. The helper already returns a Boolean, so the call goes straight into the if.
    8. Return count after the loop.

    The solution in Scala

    class Solution {
        def isPrime(n: Int): Boolean = {
            if (n < 2) {
                return false
            }
            for (d <- 2 until n) {
                if (n % d == 0) {
                    return false
                }
            }
            return true
        }
    
        def countPrimes(nums: Array[Int]): Int = {
            var count = 0
            for (num <- nums) {
                if (isPrime(num)) {
                    count += 1
                }
            }
            return count
        }
    }
    

    Scala details worth knowing:

    • 2 until n excludes n. 2 to n would include it, and n % n == 0 would make every number look composite. until is the right choice here.
    • return inside a for. A for loop over a range is turned into a call that takes a function, so this return leaves the whole method from inside that function. Scala 3.5 compiles and runs it, but prints a warning that such non-local returns are no longer supported and suggests scala.util.boundary. The lesson's tests are not affected.
    • % is the remainder. n % d == 0 means d divides n with nothing left over.
    • var versus val. count += 1 reassigns the variable, so val would be rejected by the compiler.

    Tracing a few numbers

    For 9, the loop tries 2 (remainder 1), then 3 (remainder 0) and returns false there, without trying 4 through 8. For 7, the loop tries 2, 3, 4, 5 and 6, finds no remainder of 0, ends, and the method returns true. For 2, there is nothing to try. The early return is what makes composite numbers cheap: the loop stops at the smallest factor.

    Complexity

    For one number n, the helper may check up to n - 2 divisors, so a prime costs O(n). A composite number usually stops much earlier, at its smallest factor. With a maximum value M and k numbers in the array, the worst case is O(k * M) time. The extra space is O(1): a counter and a loop variable.

    The constraint allows values up to 100000, so the simple search stays fast for the lesson. A common speed-up checks only divisors up to the square root of n, since a larger divisor always pairs with a smaller one. The lesson doesn't need it.

    Edge cases and common mistakes

    • 0 and 1. Without the first check, the loop for 1 is empty and the helper would return true, which is wrong. The check n < 2 prevents that.
    • 2. It is the smallest prime. The range 2 until 2 is empty, so the helper returns true, which is correct.
    • Squares of primes. 4 and 9 must be rejected: 4 % 2 == 0 and 9 % 3 == 0.
    • Returning true inside the loop. A number that isn't divisible by one d may still be divisible by another. Only the end of the loop proves primality.
    • Returning inside the counting loop. It would stop after the first number instead of checking all of them.
    • Removing duplicates. Don't. The statement counts each appearance, 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(2) gives true, isPrime(1) gives false, isPrime(97) gives true and isPrime(99991) gives true.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free