Problem overview
Given a vector nums, count_primes returns how many of its numbers are prime. A prime is greater than 1 and divisible only by 1 and itself, so 2, 3, 5, 7, 11 are prime and 0 and 1 are not. A number that appears twice counts twice. The helper is_prime decides for one number, and count_primes goes over the vector and counts the true answers. 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.
Approach: trial division
To decide whether n is prime, try to find a divisor. If any number from 2 to n - 1 divides n evenly, then n is not prime, and one divisor is enough to know. If the search ends with none, n is prime. Numbers below 2 are rejected first, because no prime is smaller than 2.
The counting function then needs a counter, a loop over the numbers, and one call to the helper per number. Each function holds a single loop: the helper's loop simply runs again for every number the second function passes to it.
Step by step
- Reject numbers below 2.
if n < 2returnsfalse. This covers 0 and 1. - Loop over candidate divisors.
for d in 2..nvisits 2 up ton - 1. The range excludes its end. - Return
falseon the first divisor.n % d == 0meansddividesnevenly. Thereturnleaves both the loop and the function. - Return
trueafter the loop. No divisor was found. - Start a counter. In
count_primes,let mut count = 0;holds the primes found so far. - Loop over
&nums. Repeated numbers are visited each time, so they count each time. - Call the helper.
Self::is_prime(*num)is already abool, so it goes straight into theif. When it is true,count += 1. - Return after the loop, once every number has been checked.
The solution in Rust
impl Solution {
fn is_prime(n: i32) -> bool {
if n < 2 {
return false;
}
for d in 2..n {
if n % d == 0 {
return false;
}
}
return true;
}
fn count_primes(nums: Vec<i32>) -> i32 {
let mut count = 0;
for num in &nums {
if Self::is_prime(*num) {
count += 1;
}
}
return count;
}
}
Rust details worth knowing:
- Ranges.
2..nis half-open: it includes 2 and excludesn. Whennis 2, the range is empty and the loop body never runs, so 2 is prime.2..nis a valid empty range even whennis smaller than 2. *num. The loop over&numsgives&i32values, andis_primetakes ani32, so the call dereferences with*.- The condition is a
bool. Rust requires the test in anifto be abool, soif Self::is_prime(*num)needs no comparison. count's type. It starts as a bare0, and the function's return type makes it ani32.
Following two numbers through the helper
Take n = 9. It is not below 2, so the loop starts with d = 2: 9 % 2 is 1, not 0. Then d = 3: 9 % 3 is 0, so the helper returns false and never looks at 4 through 8. Now take n = 7. The loop tries 2, 3, 4, 5 and 6, and none of them divides 7, so the loop ends and the helper returns true. A prime is the only kind of number that makes the helper try every candidate. For 0 and 1 the loop would never run, so only the first check keeps them from being reported as prime.
The counting function never needs to know how primality is tested. It asks a yes-or-no question about each number and adds 1 for every yes, which is why the helper could later be replaced by a faster test without touching the loop.
Complexity
For a single number n, is_prime runs at most n - 2 remainder checks. A prime is the worst case, because the loop runs to the end. A composite number usually stops much earlier: 100000 stops at its first check, with d = 2. Across the vector, the time is the sum of those costs, which is at most the length of nums times about 100000 for the lesson's largest values. The extra space is O(1).
Checking divisors only up to the square root of n would be much faster, because a composite number always has a divisor no larger than its square root. The lesson keeps the full range so the idea stays simple.
Edge cases and common mistakes
- 0 and 1. Without the
n < 2guard, the loop for 0 or 1 never runs and the helper returnstrue. A version with no guard returnstruefor 0, 1 and even -7. - 2. It is the smallest prime, and the empty loop correctly leaves it as prime.
- Repeated values.
[7, 10, 7]gives 2, because each 7 is counted. - Returning inside the counting loop. The function would stop after the first number.
- A
return trueinside the divisor loop. That would declare a number prime after its first non-divisor, long before the others have been tried.
Testing
[2, 3, 4, 5, 6]gives3.[0, 1, 9]gives0.[7, 10, 7]gives2.is_primeon 97 givestrueand on 9 givesfalse; on 99991 it givestrue.
