Problem overview
Given an array nums, countPrimes returns how many of its numbers are prime. A prime is greater than 1 and divisible evenly only by 1 and itself. 0 and 1 are not prime, and a prime that appears twice counts twice.
The lesson splits the work into a helper, isPrime(n), which answers true or false for one number, and countPrimes, which loops over the array and counts the numbers the helper accepts. For [2, 3, 4, 5, 6] the answer is 3 (2, 3 and 5). For [0, 1, 9] it is 0. For [7, 10, 7] it is 2, because 7 counts at each appearance.
Approach: test one number, then count
To decide whether n is prime, look for a divisor. Any number from 2 to n - 1 that divides n evenly proves n is not prime, and one divisor is enough to stop. If the search finds none, n is prime. Numbers below 2 are rejected before the search, since no prime is smaller than 2.
The counting method then does what any counting loop does: start at 0, visit every number, and add 1 when the helper says yes. The helper has a loop of its own, but countPrimes only calls it and doesn't need to know how it works.
Step by step
- Reject numbers below 2. In
isPrime, ifn < 2, returnfalse. This handles 0 and 1. - Loop over the candidate divisors with
for (d <- 2 until n), which covers 2 up ton - 1. Forn = 2the range is empty, so the loop body never runs. - Return
falseon the first divisor. Whenn % d == 0,ddividesnevenly.returnleaves the loop and the method at once. - Return
trueafter the loop. If no divisor was found, the number is prime. - In
countPrimes, createvar count = 0. It has to be avarbecause it changes. - Loop over
numswithfor (num <- nums). A repeated number is visited twice, so it counts twice. - Add 1 when
isPrime(num)is true. The helper already returns aBoolean, so the call goes straight into theif. - Return
countafter the loop.
The solution in Scala
class Solution {
def isPrime(n: Int): Boolean = {
if (n < 2) {
return false
}
for (d <- 2 until n) {
if (n % d == 0) {
return false
}
}
return true
}
def countPrimes(nums: Array[Int]): Int = {
var count = 0
for (num <- nums) {
if (isPrime(num)) {
count += 1
}
}
return count
}
}
Scala details worth knowing:
2 until nexcludesn.2 to nwould include it, andn % n == 0would make every number look composite.untilis the right choice here.returninside afor. Aforloop over a range is turned into a call that takes a function, so thisreturnleaves the whole method from inside that function. Scala 3.5 compiles and runs it, but prints a warning that such non-local returns are no longer supported and suggestsscala.util.boundary. The lesson's tests are not affected.%is the remainder.n % d == 0meansddividesnwith nothing left over.varversusval.count += 1reassigns the variable, sovalwould be rejected by the compiler.
Tracing a few numbers
For 9, the loop tries 2 (remainder 1), then 3 (remainder 0) and returns false there, without trying 4 through 8. For 7, the loop tries 2, 3, 4, 5 and 6, finds no remainder of 0, ends, and the method returns true. For 2, there is nothing to try. The early return is what makes composite numbers cheap: the loop stops at the smallest factor.
Complexity
For one number n, the helper may check up to n - 2 divisors, so a prime costs O(n). A composite number usually stops much earlier, at its smallest factor. With a maximum value M and k numbers in the array, the worst case is O(k * M) time. The extra space is O(1): a counter and a loop variable.
The constraint allows values up to 100000, so the simple search stays fast for the lesson. A common speed-up checks only divisors up to the square root of n, since a larger divisor always pairs with a smaller one. The lesson doesn't need it.
Edge cases and common mistakes
- 0 and 1. Without the first check, the loop for 1 is empty and the helper would return
true, which is wrong. The checkn < 2prevents that. - 2. It is the smallest prime. The range
2 until 2is empty, so the helper returnstrue, which is correct. - Squares of primes. 4 and 9 must be rejected:
4 % 2 == 0and9 % 3 == 0. - Returning
trueinside the loop. A number that isn't divisible by onedmay still be divisible by another. Only the end of the loop proves primality. - Returning inside the counting loop. It would stop after the first number instead of checking all of them.
- Removing duplicates. Don't. The statement counts each appearance, so
[7, 10, 7]gives 2.
Testing
[2, 3, 4, 5, 6]gives3.[0, 1, 9]gives0.[7, 10, 7]gives2.isPrime(2)givestrue,isPrime(1)givesfalse,isPrime(97)givestrueandisPrime(99991)givestrue.
