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
- In
IsPrime, returnfalsewhenn < 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 returntruefor them. - Loop with
for (int d = 2; d < n; d++). Eachdis a candidate divisor. A prime has none between 2 andn - 1. - Inside the loop, return
falseifn % d == 0. The%operator gives the remainder, and a remainder of 0 meansddividesnevenly. One divisor is enough, andreturnstops both the loop and the method. - After the loop, return
true. The loop ended without finding a divisor. - In
CountPrimes, createint count = 0. No number has been checked yet. - Loop with
foreach (int num in nums). A number that appears twice is visited twice, so it is counted twice. - Inside the loop,
if (IsPrime(num))thencount++. The helper's answer is already abool, so the call goes straight into theif. There is no need to write== true, and comparing abooltotrueonly adds noise. The helper has its own loop, which runs again for every number. - Return
countafter 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.trueandfalseare lowercase too, unlike in Python. count++adds 1 tocount. It is shorthand forcount = count + 1.%works on negative numbers too, but herenis 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 < 2test.CountPrimes(new int[] { 0, 1, 9 })returns 0. - 2 is prime. The loop starts at
d = 2and the conditiond < nis false at once forn = 2, so the method returnstrue.IsPrime(2)isTrue. - Starting the loop at 1. Every
nis 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
nums | Result |
|---|---|
[2, 3, 4, 5, 6] | 3 |
[0, 1, 9] | 0 |
[7, 10, 7] | 2 |
[2] | 1 |
[99991] | 1 |
