Start learning free

LESSON 241 OF 671 · HELPER FUNCTIONS

Count Primes in Java: An isPrime Helper and a Counting Loop

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

    JAVA · HELPER FUNCTIONS

    Count Primes in Java, explained

    Problem overview

    Given an int[] named nums, countPrimes returns how many of its numbers are prime. A prime is greater than 1 and divisible evenly only by 1 and by itself: 2, 3, 5, 7, 11, 13 and so on. 0 and 1 are not prime. A number that appears twice counts twice.

    The work is split in two methods. The helper isPrime(int n) answers true or false for one number. The method countPrimes(int[] nums) goes over the array and counts the numbers the helper accepts.

    For [2, 3, 4, 5, 6] the answer is 3, for the primes 2, 3 and 5. For [0, 1, 9] it is 0, since 0 and 1 are never prime and 9 is 3 times 3. For [7, 10, 7] it is 2: 7 is prime and appears twice.

    Approach

    Counting and testing primality are two different jobs, so each gets its own method. countPrimes is a plain counting loop, the same shape as counting the even numbers or the negative ones, with the question "is this one prime?" delegated to a method. isPrime only has to handle one number and doesn't know about arrays.

    To test one number n, look for a divisor. If any number from 2 up to n - 1 divides n evenly, n isn't prime, and you can stop at the first one you find. If the search ends with no divisor, n is prime. Numbers below 2 are handled first, because they have no divisor in that range yet still aren't prime.

    Step by step

    The helper, isPrime

    1. If n < 2, return false. This covers 0 and 1, and no prime is smaller than 2.
    2. Write a for loop with an int d that starts at 2 and goes up by one while d < n. Each d is a candidate divisor.
    3. Inside the loop, if n % d == 0, return false. The % operator gives the remainder, and a remainder of 0 means d divides n evenly. One divisor is enough, and return leaves both the loop and the method.
    4. After the loop, return true. The loop finished without finding any divisor.

    The counter, countPrimes

    1. Create an int named count and start it at 0: nothing has been checked yet.
    2. Write a for-each loop with an int named num over nums. A number that appears twice is visited twice, so it counts twice.
    3. Inside the loop, if (isPrime(num)), add 1 to count with count++. The call already produces a boolean, so it goes straight into the if with no == true.
    4. After the loop, return count. Returning inside the loop would stop after the first number.

    The solution in Java

    class Solution {
        public boolean isPrime(int n) {
            if (n < 2) {
                return false;
            }
            for (int d = 2; d < n; d++) {
                if (n % d == 0) {
                    return false;
                }
            }
            return true;
        }
    
        public int countPrimes(int[] nums) {
            int count = 0;
            for (int num : nums) {
                if (isPrime(num)) {
                    count++;
                }
            }
            return count;
        }
    }
    

    Java details in this code:

    • Two loops, one per method. The helper's loop runs again from scratch for every number the outer loop passes it. Each method's variables are its own, so d and n don't clash with count and num.
    • A boolean return. isPrime is declared boolean, and every path ends in return true or return false. If the final return true; were missing, the method wouldn't compile.
    • Calls by name. Both methods belong to Solution, so countPrimes calls isPrime(num) without an object in front.
    • % with int. n % d is the remainder of integer division, and it is 0 exactly when d divides n.

    Complexity

    For a prime n, the helper tries every d from 2 to n - 1, so it takes O(n) time. For a number like 100000, the loop stops at d = 2, much sooner. With k numbers of size up to M, the worst case is O(k * M) time, and the extra space is O(1). With values up to 100000, that is fast enough.

    A common refinement is to stop the search once d * d exceeds n: a divisor larger than the square root of n always comes paired with a smaller one that the loop would already have found. The lesson's version keeps the simpler bound.

    Edge cases and common mistakes

    • 0 and 1. Without the n < 2 check, the loop for 1 doesn't run at all (it starts at 2, and 2 is not less than 1), and the method would return true for 1 and for 0. With the check, isPrime(0) and isPrime(1) are false.
    • 2 is prime. It is the only even prime. For n = 2 the loop doesn't run, since d = 2 is not less than 2, and the method returns true.
    • Squares of primes. A number like 9 has the divisor 3, which the loop reaches before it ends. isPrime(9) returns false.
    • Putting return true inside the loop. Writing an else { return true; } inside the loop would declare n prime after testing only d = 2. The true belongs after the loop.
    • Counting distinct primes. The task counts every appearance, so no set is needed.

    Testing

    • countPrimes(new int[]{2, 3, 4, 5, 6}) returns 3.
    • countPrimes(new int[]{0, 1, 9}) returns 0.
    • countPrimes(new int[]{7, 10, 7}) returns 2.
    • countPrimes(new int[]{99991, 100000}) returns 1.

    For the helper, isPrime(0), isPrime(1) and isPrime(9) return false, while isPrime(2), isPrime(13) and isPrime(97) return true.

    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free