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
- If
n < 2, returnfalse. This covers 0 and 1, and no prime is smaller than 2. - Write a
forloop with anintdthat starts at 2 and goes up by one whiled < n. Eachdis a candidate divisor. - Inside the loop, if
n % d == 0, returnfalse. The%operator gives the remainder, and a remainder of 0 meansddividesnevenly. One divisor is enough, andreturnleaves both the loop and the method. - After the loop, return
true. The loop finished without finding any divisor.
The counter, countPrimes
- Create an
intnamedcountand start it at 0: nothing has been checked yet. - Write a for-each loop with an
intnamednumovernums. A number that appears twice is visited twice, so it counts twice. - Inside the loop,
if (isPrime(num)), add 1 tocountwithcount++. The call already produces aboolean, so it goes straight into theifwith no== true. - 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
dandndon't clash withcountandnum. - A
booleanreturn.isPrimeis declaredboolean, and every path ends inreturn trueorreturn false. If the finalreturn true;were missing, the method wouldn't compile. - Calls by name. Both methods belong to
Solution, socountPrimescallsisPrime(num)without an object in front. %withint.n % dis the remainder of integer division, and it is 0 exactly whenddividesn.
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 < 2check, the loop for 1 doesn't run at all (it starts at 2, and 2 is not less than 1), and the method would returntruefor 1 and for 0. With the check,isPrime(0)andisPrime(1)arefalse. - 2 is prime. It is the only even prime. For
n = 2the loop doesn't run, sinced = 2is not less than 2, and the method returnstrue. - Squares of primes. A number like 9 has the divisor 3, which the loop reaches before it ends.
isPrime(9)returnsfalse. - Putting
return trueinside the loop. Writing anelse { return true; }inside the loop would declarenprime after testing onlyd = 2. Thetruebelongs 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.
