Start learning free

LESSON 244 OF 291 · HELPER FUNCTIONS

Count Primes in Kotlin: A Primality 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

    KOTLIN · HELPER FUNCTIONS

    Count Primes in Kotlin, explained

    Problem overview

    Given an IntArray named nums, return how many of its numbers are prime. A prime is greater than 1 and divisible evenly only by 1 and itself: 2, 3, 5, 7, 11 and so on. 0 and 1 are not prime. If a number appears more than once, every appearance counts.

    The work is split between two functions. The helper isPrime answers one question about one number: prime or not. The function that is checked, countPrimes, goes over the array and counts the numbers for which the helper says true.

    For [2, 3, 4, 5, 6] the answer is 3 (2, 3 and 5). For [0, 1, 9] it is 0, because 0 and 1 are never prime and 9 is 3 times 3. For [7, 10, 7] it is 2, since 7 is prime and counts twice.

    Approach

    Deciding whether one number is prime and counting over an array are two separate problems, so each gets its own function. The helper can be written and checked on its own, and the counting function becomes a plain loop with a counter.

    For the helper, use the definition directly. A number below 2 is not prime. Any other number n is prime unless some d from 2 to n - 1 divides it evenly. One such divisor is enough to answer false, so the helper can return the moment it finds one. If the loop ends without finding any, the number is prime.

    Take 9 as an example. The helper tries d = 2, and 9 % 2 is 1, so it goes on. With d = 3, 9 % 3 is 0, so it returns false without trying 4 to 8. For 7, no value from 2 to 6 divides it, the loop ends, and the helper returns true.

    Step by step

    The helper. Start with the small numbers: if n < 2, return false. This covers 0 and 1, and without it the loop below would have nothing to test and the helper would wrongly answer true.

    Then a for loop lets d go over 2 until n, the numbers from 2 to n - 1. Inside it, n % d == 0 means d divides n evenly, so return false at once. That stops both the loop and the function. After the loop, return true: no divisor was found.

    The counting function. countPrimes creates var count = 0, because nothing has been checked yet. A for loop visits each num in nums. If isPrime(num) is true, count++ adds 1. The helper already returns a Boolean, so its call goes straight into the if. A repeated number is visited each time it appears, so it counts each time. After the loop, return count.

    The solution in Kotlin

    class Solution {
        fun isPrime(n: Int): Boolean {
            if (n < 2) {
                return false
            }
            for (d in 2 until n) {
                if (n % d == 0) {
                    return false
                }
            }
            return true
        }
    
        fun countPrimes(nums: IntArray): Int {
            var count = 0
            for (num in nums) {
                if (isPrime(num)) {
                    count++
                }
            }
            return count
        }
    }
    

    Some Kotlin details:

    • 2 until n is a range that includes 2 and excludes n, so the loop never tests n against itself. For n = 2 and n = 3 the range is empty or just 2: the helper returns true for 2 without running the body, and for 3 it tests 3 % 2.
    • % is the remainder operator. n % d == 0 is the usual "divides evenly" test.
    • count++ adds 1 to a var. A val would not compile here, because it can't be reassigned.
    • Both functions are members of Solution, so countPrimes calls isPrime(num) by name.

    Complexity

    For one number n, the helper tries up to n - 2 divisors, so it takes O(n) time in the worst case: when n is prime, or has no small divisor. Composite numbers usually stop early. For example, any even number above 2 returns at d = 2. Over an array of k numbers each at most M, countPrimes takes O(k · M) in the worst case. With values up to 100000 that is comfortable. The extra space is O(1): a few variables.

    The loop could stop at the square root of n, since a divisor larger than the root pairs with a smaller one. This lesson keeps the plain version, which follows the definition.

    Edge cases and common mistakes

    • 0 and 1. Without the n < 2 check, both would pass the loop with nothing to test and be reported as prime. isPrime(1) returns false only because of that check.
    • Starting the divisors at 1. Every number is divisible by 1, so a loop from 1 would call every number composite. Start at 2.
    • Including n as a divisor. Every number is divisible by itself. That is why the range stops before n.
    • Returning true inside the loop. A number that fails to divide by 2 isn't necessarily prime. Only after every candidate has been tried can the helper answer true.
    • Returning inside the counting loop. That would stop after the first number.
    • Duplicates. Don't remove them: the task counts each appearance.

    Testing

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