Start learning free

LESSON 247 OF 293 · HELPER FUNCTIONS

Count Primes in Rust: A Helper with Trial Division

Practice Read the full explanation

Given an array of integers nums, return how many of them are prime numbers.

A prime number is greater than 1 and can be divided evenly only by 1 and by itself: 2, 3, 5, 7, 11, 13 and so on. 0 and 1 are not prime. If a number appears more than once, each appearance counts.

The work is split between two functions. The first one is a helper: it gets one number and returns true if it is prime, false if it is not. The second one, the function that is graded, goes over the numbers and counts the ones the helper says are prime.

 

Example 1:

Input: nums = [2, 3, 4, 5, 6]
Output: 3
Explanation: 2, 3 and 5 are prime. 4 = 2 × 2 and 6 = 2 × 3 are not.

Example 2:

Input: nums = [0, 1, 9]
Output: 0
Explanation: 0 and 1 are never prime, and 9 = 3 × 3.

Example 3:

Input: nums = [7, 10, 7]
Output: 2
Explanation: 7 is prime and appears twice, so it counts twice. 10 = 2 × 5 is not prime.

 

Constraints:

  • nums has at least one number.
  • Every number is an integer from 0 to 100000.
STEP 1 OF 8
    Ctrl + Enter to check

    RUST · HELPER FUNCTIONS

    Count Primes in Rust, explained

    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

    1. Reject numbers below 2. if n < 2 returns false. This covers 0 and 1.
    2. Loop over candidate divisors. for d in 2..n visits 2 up to n - 1. The range excludes its end.
    3. Return false on the first divisor. n % d == 0 means d divides n evenly. The return leaves both the loop and the function.
    4. Return true after the loop. No divisor was found.
    5. Start a counter. In count_primes, let mut count = 0; holds the primes found so far.
    6. Loop over &nums. Repeated numbers are visited each time, so they count each time.
    7. Call the helper. Self::is_prime(*num) is already a bool, so it goes straight into the if. When it is true, count += 1.
    8. 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..n is half-open: it includes 2 and excludes n. When n is 2, the range is empty and the loop body never runs, so 2 is prime. 2..n is a valid empty range even when n is smaller than 2.
    • *num. The loop over &nums gives &i32 values, and is_prime takes an i32, so the call dereferences with *.
    • The condition is a bool. Rust requires the test in an if to be a bool, so if Self::is_prime(*num) needs no comparison.
    • count's type. It starts as a bare 0, and the function's return type makes it an i32.

    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 < 2 guard, the loop for 0 or 1 never runs and the helper returns true. A version with no guard returns true for 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 true inside 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] gives 3.
    • [0, 1, 9] gives 0.
    • [7, 10, 7] gives 2.
    • is_prime on 97 gives true and on 9 gives false; on 99991 it gives true.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free