Problem overview
Given an array of integers nums, countPrimes returns how many of them are prime. A prime is greater than 1 and divisible only by 1 and itself: 2, 3, 5, 7, 11 and so on. The numbers 0 and 1 are not prime. A number that appears several times counts every time.
The work is split between two methods. The helper isPrime answers one question about one number, and countPrimes asks it about every element. For [2, 3, 4, 5, 6] the answer is 3, because 2, 3 and 5 are prime while 4 and 6 are not. For [0, 1, 9] it is 0, and for [7, 10, 7] it is 2, since the prime 7 counts twice.
Approach
To test one number n, look for a divisor between 2 and n - 1. If any number in that range divides n evenly, n is not prime, and the search can stop at once. If the whole range is checked without a hit, n is prime. Numbers below 2 are rejected before the search, because no prime is smaller than 2.
Counting is the usual pattern: a counter starts at 0, a loop visits each number, and the counter goes up whenever the helper says true. Splitting the work this way means each method has one loop and one job. The helper's loop runs again for each number, but countPrimes never needs to know how primality is tested.
How the helper decides
For 9 the loop tries d = 2, where 9 % 2 is 1, then d = 3, where 9 % 3 is 0, so the function returns false and never tries 4 to 8. For 7 the loop tries 2, 3, 4, 5 and 6, finds no remainder of 0, leaves the loop and returns true. For 2 there is nothing to try at all, and the answer is true straight away. The early return is what keeps composite numbers cheap: most of them are rejected within the first few values of d.
Notice that countPrimes contains no divisibility logic. It only decides what to do with each answer, which keeps both methods short enough to read at a glance.
Step by step
- Reject numbers below 2. If
n < 2, returnfalse. - Loop over the candidate divisors.
dgoes over2..<n, which covers 2 up ton - 1. - Test each one. If
n % d == 0,ddividesn, so returnfalseimmediately. This also ends the loop. - Return
trueafter the loop. No divisor was found. - In
countPrimes, createcountwithvar, starting at 0. - Loop over
nums. The loop variable isnum, and repeated numbers are visited repeatedly. - Count the primes. If
isPrime(num), add 1 withcount += 1. The helper already returns aBool, so the call goes straight into theif. - Return
countafter the loop. Returning inside the loop would stop after the first number.
The solution in Swift
class Solution {
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for d in 2..<n {
if n % d == 0 {
return false
}
}
return true
}
func countPrimes(_ nums: [Int]) -> Int {
var count = 0
for num in nums {
if isPrime(num) {
count += 1
}
}
return count
}
}
Swift details worth knowing:
- The guard on
n < 2protects the range. A range2..<nwithnbelow 2 is invalid, and creating one crashes the program at run time. After the guard, the smallestnis 2, and2..<2is a valid empty range, soisPrime(2)skips the loop and returnstrue. ..<excludes the upper bound.2..<nnever includesnitself, which is what the check needs: every number divides itself.%is the remainder operator.n % d == 0meansddividesnevenly.- Calling a sibling method needs only its name,
isPrime(num), and the underscores in the signature mean no argument labels.
Complexity
For a single number n, the helper does at most n - 2 remainder checks, so it is O(n). A composite number usually stops early, at its smallest divisor, while a prime runs the loop to the end. For an array of k numbers with values up to M, countPrimes costs O(k * M) in the worst case. It uses O(1) extra space. Stopping the divisor search at the square root of n would be much faster, since a divisor above the square root always has a partner below it, but for the lesson's limits the plain loop is enough.
For reference, here is that faster test as a free function. It uses a while loop that stops once d * d passes n:
func isPrimeFast(_ n: Int) -> Bool {
if n < 2 {
return false
}
var d = 2
while d * d <= n {
if n % d == 0 {
return false
}
d += 1
}
return true
}
For the inputs [0, 1, 2, 3, 4, 9, 97, 100000, 99991] it returns [false, false, true, true, false, false, true, false, true].
Edge cases and common mistakes
- 0 and 1. They are not prime, and the guard handles them before the range is created.
- 2. The only even prime. The loop is empty, so it returns
true. - Repeated numbers.
[7, 10, 7]gives 2: each appearance counts, so do not collapse the array into a set. - Starting the loop at 1. Every number is divisible by 1, so
isPrimewould answerfalsefor every input. - Including
nin the range. Writing2...nwould findn % n == 0and reject every number.
Testing
[2, 3, 4, 5, 6]gives 3.[0, 1, 9]gives 0.[7, 10, 7]gives 2.isPrime(97)istrue,isPrime(2)istrue,isPrime(1)isfalseandisPrime(100000)isfalse.
