Start learning free

LESSON 243 OF 289 · HELPER FUNCTIONS

Count Primes in C#: Calling an IsPrime Helper

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

    C# · HELPER FUNCTIONS

    Count Primes in C#, explained

    Problem overview

    Given an int[] named nums, CountPrimes returns how many of its numbers are prime. A prime is greater than 1 and divisible evenly only by 1 and by itself: 2, 3, 5, 7, 11 and so on. 0 and 1 are not prime. A number that appears several times counts each time.

    The work is split between two methods. IsPrime(int n) is a helper that answers true or false for one number. CountPrimes loops over the array and counts the numbers the helper accepts. 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, because 7 is prime and is counted twice.

    Approach: one question per method

    Each method answers one question. IsPrime asks "does this number have a divisor other than 1 and itself?" and CountPrimes asks "how many numbers pass that test?". Neither needs to know how the other works. CountPrimes just calls IsPrime(num) and trusts the answer.

    For the helper, the definition gives the method directly. Rule out numbers below 2 first. For the rest, try every possible divisor d from 2 up to n - 1. If any of them divides n evenly, n is not prime, and there is no need to keep looking. If none does, n is prime.

    Step by step

    1. In IsPrime, return false when n < 2. 0 and 1 are not prime, and neither is any negative number. Without this test, the loop below would be skipped for 0 and 1 and the method would wrongly return true for them.
    2. Loop with for (int d = 2; d < n; d++). Each d is a candidate divisor. A prime has none between 2 and n - 1.
    3. Inside the loop, return false if n % d == 0. The % operator gives the remainder, and a remainder of 0 means d divides n evenly. One divisor is enough, and return stops both the loop and the method.
    4. After the loop, return true. The loop ended without finding a divisor.
    5. In CountPrimes, create int count = 0. No number has been checked yet.
    6. Loop with foreach (int num in nums). A number that appears twice is visited twice, so it is counted twice.
    7. Inside the loop, if (IsPrime(num)) then count++. The helper's answer is already a bool, so the call goes straight into the if. There is no need to write == true, and comparing a bool to true only adds noise. The helper has its own loop, which runs again for every number.
    8. Return count after the loop, so every number is checked first.

    The solution in C#

    class Solution {
        public bool IsPrime(int n) {
            if (n < 2) {
                return false;
            }
            for (int d = 2; d < n; d++) {
                if (n % d == 0) {
                    return false;
                }
            }
            return true;
        }
    
        public int CountPrimes(int[] nums) {
            int count = 0;
            foreach (int num in nums) {
                if (IsPrime(num)) {
                    count++;
                }
            }
            return count;
        }
    }
    

    C# details:

    • The type for true and false is bool, in lowercase. true and false are lowercase too, unlike in Python.
    • count++ adds 1 to count. It is shorthand for count = count + 1.
    • % works on negative numbers too, but here n is at least 2 whenever the loop runs, so the remainders are always the plain ones.
    • The two methods call each other by name. Both live in the class Solution, so no object or prefix is needed.

    Following the helper by hand

    Take IsPrime(9). The number is not below 2, so the loop starts with d = 2. Nine divided by 2 leaves remainder 1, so nothing happens. With d = 3 the remainder is 0, so the method returns false and never tries 4 through 8. Now take IsPrime(7). The loop tries 2, 3, 4, 5 and 6, each leaves a non-zero remainder, the condition d < n then fails, and the line after the loop returns true. A true answer always costs the whole loop, while a false answer can come early.

    Complexity

    For a prime n, the helper tries every divisor from 2 to n - 1, so it takes O(n) steps. For a number such as 100000 it stops at the first divisor, 2. The worst case is a large prime: IsPrime(99991) returns True after about a hundred thousand remainder checks, which a computer does in a blink. Since the numbers are at most 100000, this simple loop is fast enough. A faster test only needs to try divisors up to the square root of n, but this lesson keeps to the plain definition.

    Edge cases and common mistakes

    • 0 and 1. Both fail the n < 2 test. CountPrimes(new int[] { 0, 1, 9 }) returns 0.
    • 2 is prime. The loop starts at d = 2 and the condition d < n is false at once for n = 2, so the method returns true. IsPrime(2) is True.
    • Starting the loop at 1. Every n is divisible by 1, so every number would be reported as not prime.
    • Counting once per distinct value. The lesson counts every appearance. The array [7, 10, 7] gives 2.
    • Returning inside the foreach. The count would stop after the first number, so the result could never be higher than 1.

    Testing

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