Problem overview
Given a slice of integers nums, return how many of them are prime. A prime is greater than 1 and divisible only by 1 and itself, so 2, 3, 5, 7, 11 and 13 are prime while 0 and 1 are not. A number that appears several times counts each time.
The work is split in two. The helper isPrime answers "is this one number prime?" with a bool. The graded function countPrimes visits every number and counts the ones the helper approves.
For [2, 3, 4, 5, 6] the answer is 3 (2, 3 and 5). For [0, 1, 9] it is 0, since 9 = 3 × 3. For [7, 10, 7] it is 2, because 7 is prime and counted twice.
Approach: test one number, then count
To test one number n, rule out everything below 2 first. Then look for a divisor: try every d from 2 up to n - 1. A single divisor proves that n is not prime, so the function can return false at once. If the loop ends without finding one, n is prime.
Counting is the usual pattern: a counter starts at 0, a loop visits each number, and the counter goes up when the helper says true. Splitting the work this way means each function has one job and one loop.
Step by step
- Return
falsewhenn < 2. This handles 0 and 1. - Write a loop with
d := 2; d < n; d++. Every possible divisor from 2 ton - 1gets a turn. - Inside it, return
falsewhenn % d == 0. The remainder is zero exactly whenddividesnevenly. - Return
trueafter the loop. No divisor was found. - In
countPrimes, createcountwith:=, starting at 0. - Loop over
numswithrange, keeping the value innumand dropping the index with_. - Call the helper in the
if:if isPrime(num), thencount++. The call already givestrueorfalse, so no comparison is needed. - Return
countafter the loop, so every number is checked first.
The solution in Go
func isPrime(n int) bool {
if n < 2 {
return false
}
for d := 2; d < n; d++ {
if n % d == 0 {
return false
}
}
return true
}
func countPrimes(nums []int) int {
count := 0
for _, num := range nums {
if isPrime(num) {
count++
}
}
return count
}
Go details:
%is the remainder operator.9 % 3is 0, and9 % 2is 1.count++is a statement, not an expression. It adds 1 tocount, but you can't writex := count++in Go.- An
iftakes abooldirectly. Go has no "truthy" values, so the condition has to be a real boolean such as the result ofisPrime(num). - Loop variables stay local.
dexists only inside itsfor, and the loop incountPrimesdoesn't interfere with the helper's loop.
Following the helper through two numbers
For n = 9 the loop tries d = 2 and gets the remainder 1, so it moves on. With d = 3 the remainder is 0, so the function returns false without trying 4 to 8.
For n = 7 the remainders for d = 2, 3, 4, 5, 6 are 1, 1, 3, 2 and 1. None is zero, the loop ends, and the function returns true.
That difference in behaviour is the point of the early return false: a composite number is rejected as soon as its smallest divisor is found, while a prime has to survive every test before it is accepted. Only the final return true, placed after the loop, can say "prime", because only then has every divisor been ruled out.
Where the work happens
Only isPrime has the inner loop over divisors. countPrimes has one loop over the numbers and calls the helper once per element, so the helper's loop starts again for every number, including repeats. A number that appears three times is tested three times and counted three times. Keeping the two loops in separate functions is what keeps each one short enough to read at a glance.
Edge cases and common mistakes
- 0, 1 and 2.
isPrime(0)andisPrime(1)arefalse. For 2 the loop starts atd = 2, and2 < 2is false, so it never runs and the function returnstrue. Without then < 2check, 0 and 1 would also fall through totrue. - Counting the divisor as the test. Starting the loop at 1 would find that every
ndivides by 1 and report no primes at all. Starting at 2 avoids that, and stopping beforenavoids dividing by itself. - Counting distinct primes. The lesson counts every appearance, so no set is needed:
[7, 10, 7]gives 2. - Returning inside the loop. Returning
countin the first turn would stop after one number. - Speed. For a prime, the helper tries every
dup ton - 1. That is fine for values up to 100000, but a divisor pair always has one member no larger than the square root ofn, so the loop conditiond * d <= nwould be enough. Checking everynfrom 0 to 100000 with both versions gives identical answers, and 9592 of those numbers are prime. The lesson keeps the simpler loop, which is easier to reason about.
Testing
isPrime(0),isPrime(1),isPrime(2),isPrime(9)andisPrime(97)givefalse,false,true,false,true.[2, 3, 4, 5, 6]gives3.[0, 1, 9]gives0.[7, 10, 7]gives2.
