Start learning free

LESSON 244 OF 289 · HELPER FUNCTIONS

Count Primes in TypeScript: A Helper That Tests One Number

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

    TYPESCRIPT · HELPER FUNCTIONS

    Count Primes in TypeScript, explained

    Problem overview

    The method countPrimes receives an array nums of integers from 0 to 100000 and returns 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 repeated number counts every time it appears.

    The work is split between two methods. The helper isPrime answers one question about one number: prime or not. countPrimes goes over the array and counts the true answers. 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.

    Approach: test each number by looking for a divisor

    A number is prime unless some number between 2 and n - 1 divides it evenly. So isPrime tries each candidate d in that range. The first one that divides n proves it isn't prime and ends the function. If none does, n is prime. Numbers below 2 are rejected before the loop.

    The counting method does not need to know how primes are tested. It calls isPrime for each number and adds 1 when the answer is true. Each method has one loop, and the helper's loop runs again for every number the other one visits.

    Step by step

    1. Reject small numbers. If n < 2, return false: no prime is smaller than 2.
    2. Write the divisor loop: for (let d = 2; d < n; d++). It tries every number from 2 up to n - 1.
    3. Return false on a divisor. If n % d === 0, d divides n evenly. % gives the remainder, and a remainder of 0 means an even division. One divisor is enough, and return stops the loop and the function.
    4. Return true after the loop. It ended without a divisor.
    5. Declare count in countPrimes as a number starting at 0.
    6. Loop over nums with for (const num of nums). A number that appears twice is visited twice.
    7. Add to the count. The call this.isPrime(num) is already true or false, so it goes straight into the if. Then count++ adds 1.
    8. Return count after the loop.

    The solution in TypeScript

    class Solution {
        isPrime(n: number): boolean {
            if (n < 2) {
                return false;
            }
            for (let d = 2; d < n; d++) {
                if (n % d === 0) {
                    return false;
                }
            }
            return true;
        }
    
        countPrimes(nums: number[]): number {
            let count: number = 0;
            for (const num of nums) {
                if (this.isPrime(num)) {
                    count++;
                }
            }
            return count;
        }
    }
    

    Language details worth knowing:

    • === for comparison. n % d === 0 compares without any type conversion. === is the usual choice in TypeScript.
    • number arithmetic. Every number is a double, and % works on whole numbers as expected here. The inputs are far below the size where integers stop being exact.
    • this.isPrime. A method calls another method of the class through this.
    • count++. It adds 1 to count, the same as count += 1.
    • Type annotations are erased. count: number and : boolean exist for the compiler and are removed in the JavaScript.

    Trying the helper on its own

    Calling isPrime on 0, 1, 2, 3, 4, 9 and 97 gives false, false, true, true, false, false and true. The first two are stopped by the n < 2 check. 2 and 3 have no candidate divisor in the range from 2 to n - 1, so the loop ends and the function returns true. 4 and 9 each have a divisor, 2 and 3, so the loop returns false before it reaches the end. 97 has none, so it runs through the whole loop.

    Testing the helper on a few numbers like this is a good habit whenever a problem is split into helper and caller: if the helper is right, a mistake in the result must be in the counting loop, and the other way round.

    Complexity

    For one number n, isPrime does at most n - 2 remainder checks: a prime goes through the whole loop, while a number with a small divisor stops early. With values up to 100000, a prime near that size takes about 100000 checks, and an array of such values multiplies that by its length. That is fine for these inputs. Stopping the loop at the square root of n would be faster, because a composite number always has a divisor that is at most its square root, but this lesson keeps the simpler test.

    Space: O(1), since only a few numbers are stored.

    Edge cases and common mistakes

    • 0 and 1. They return false from the first check. Without it, the loop would not run for 1, and 1 would be reported as prime.
    • 2. The loop starts at 2 and needs d < 2, so it doesn't run, and 2 is correctly prime. countPrimes([2]) returns 1.
    • Repeats. [7, 10, 7] returns 2, because each 7 is counted.
    • Loop bound. Using d <= n would test n % n, which is always 0, and no number would be prime.
    • Starting at 1. Every number is divisible by 1, so a loop starting there would reject everything.
    • Returning inside the counting loop. That would stop after the first number.

    Testing

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