Problem overview
Given a list of integers nums, return how many of them are prime. A prime is greater than 1 and divisible only by 1 and itself. 0 and 1 are not prime, and a number that appears twice counts twice.
The work is split in two methods. isPrime is a helper that takes one number and returns True or False. countPrimes loops over the list and counts the numbers the helper accepts. 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, because the prime 7 appears twice.
Approach
To show that n is not prime, one divisor between 2 and n - 1 is enough. To show that it is prime, no such divisor may exist. So the helper tries each candidate d in turn and gives up with False as soon as one divides n evenly. If the loop finishes without a hit, the answer is True.
Numbers below 2 need a special case first: the loop over range(2, n) would be empty for 0 and 1, and the helper would wrongly report them as prime.
The counting method then uses the helper like any other yes/no question: one loop, one counter, one if.
Step by step
- In
isPrime, returnFalseifn < 2. No prime is smaller than 2. - Loop
doverrange(2, n), the numbers from 2 ton - 1. - If
n % d == 0, returnFalse. The remainder is 0 whenddividesnevenly. One divisor settles the question, andreturnstops the loop and the function at once. - Return
Trueafter the loop. No divisor was found. - In
countPrimes, setcount = 0. Nothing has been counted yet. - Loop
numovernums. A repeated number is visited each time it appears, so it counts each time. - If
self.isPrime(num)is true, add 1 tocount. The call already returnsTrueorFalse, so it goes straight into theif. - Return
countafter the loop, once every number has been checked.
The solution in Python
class Solution:
def isPrime(self, n: int) -> bool:
if n < 2:
return False
for d in range(2, n):
if n % d == 0:
return False
return True
def countPrimes(self, nums: List[int]) -> int:
count = 0
for num in nums:
if self.isPrime(num):
count += 1
return count
Python details:
range(2, n)excludesn. It yields 2 up ton - 1. Forn = 2it is empty, and forn = 3it holds only 2, which does not divide 3. Both fall through toTrue, which is right.%gives the remainder. For positive numbers,n % d == 0meansddividesnexactly.- Two loops, two functions. Each function has its own loop and its own variables.
countPrimesonly callsisPrime, which runs its loop again for every number.
Tracing the helper
For n = 9, the loop tries d = 2 (remainder 1) and d = 3 (remainder 0). At d = 3 the test n % d == 0 is true, so isPrime(9) returns False without trying 4 to 8.
For n = 7, the remainders for d = 2 to 6 are 1, 1, 3, 2 and 1. None is 0, so the loop ends and the function returns True. A prime always runs the whole loop, while a composite number stops at its smallest divisor.
The range is also why the edge cases work. range(2, 2) is empty and range(2, 3) holds only 2, so for n = 2 and n = 3 the loop finds no divisor and the function returns True.
A faster divisor search
The reference loop tests every d up to n - 1, but that is more than needed. If n has a divisor, it has one no larger than its square root. For 99991 the integer square root is 316, so about 315 tests would be enough instead of nearly 100000. The lesson's version keeps the loop simple; the square-root bound is an optimisation to try once the basic version works.
Complexity
For one number n, isPrime does at most about n divisions, and it does the full amount for a prime. For a list of k numbers up to 100000, the total work is at most about k * 100000 divisions. That is fine for the lesson's inputs. Faster tests stop at the square root of n, because a number with a divisor has one no larger than its square root, but the simple loop is enough here. Extra space is a few integers.
Edge cases and common mistakes
- 0 and 1. Without the
n < 2check, both would returnTrue, since the loop overrange(2, n)is empty.[0, 1, 9]would then count 2 instead of 0. - 2 is prime. It is the only even prime, and the code handles it with no special case.
- Returning
Trueinside the loop. Finding thatddoes not dividenproves nothing. Only after everydhas failed isnprime. - Returning
countinside the loop stops after the first number. - Duplicates. The list is not turned into a set, so
[7, 10, 7]gives 2.
Testing
[2, 3, 4, 5, 6]gives3.[0, 1, 9]gives0.[7, 10, 7]gives2.isPrimeon 0, 1, 2, 3, 4, 9 and 97 givesFalse, False, True, True, False, False, True.[99991]gives1: 99991 is prime.
