Problem overview
The method countPrimes receives an array nums of integers from 0 to 100000 and returns 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 repeated number counts every time it appears.
The work is split between two methods. The helper isPrime answers one question about one number: prime or not. countPrimes goes over the array 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: test each number by looking for a divisor
A number is prime unless some number between 2 and n - 1 divides it evenly. So isPrime tries each candidate d in that range. The first one that divides n proves it isn't prime and ends the function. If none does, n is prime. Numbers below 2 are rejected before the loop.
The counting method does not need to know how primes are tested. It calls isPrime for each number and adds 1 when the answer is true. Each method has one loop, and the helper's loop runs again for every number the other one visits.
Step by step
- Reject small numbers. If
n < 2, returnfalse: no prime is smaller than 2. - Write the divisor loop:
for (let d = 2; d < n; d++). It tries every number from 2 up ton - 1. - Return
falseon a divisor. Ifn % d === 0,ddividesnevenly.%gives the remainder, and a remainder of 0 means an even division. One divisor is enough, andreturnstops the loop and the function. - Return
trueafter the loop. It ended without a divisor. - Declare
countincountPrimesas a number starting at 0. - Loop over
numswithfor (const num of nums). A number that appears twice is visited twice. - Add to the count. The call
this.isPrime(num)is alreadytrueorfalse, so it goes straight into theif. Thencount++adds 1. - Return
countafter the loop.
The solution in TypeScript
class Solution {
isPrime(n: number): boolean {
if (n < 2) {
return false;
}
for (let d = 2; d < n; d++) {
if (n % d === 0) {
return false;
}
}
return true;
}
countPrimes(nums: number[]): number {
let count: number = 0;
for (const num of nums) {
if (this.isPrime(num)) {
count++;
}
}
return count;
}
}
Language details worth knowing:
===for comparison.n % d === 0compares without any type conversion.===is the usual choice in TypeScript.numberarithmetic. Every number is a double, and%works on whole numbers as expected here. The inputs are far below the size where integers stop being exact.this.isPrime. A method calls another method of the class throughthis.count++. It adds 1 tocount, the same ascount += 1.- Type annotations are erased.
count: numberand: booleanexist for the compiler and are removed in the JavaScript.
Trying the helper on its own
Calling isPrime on 0, 1, 2, 3, 4, 9 and 97 gives false, false, true, true, false, false and true. The first two are stopped by the n < 2 check. 2 and 3 have no candidate divisor in the range from 2 to n - 1, so the loop ends and the function returns true. 4 and 9 each have a divisor, 2 and 3, so the loop returns false before it reaches the end. 97 has none, so it runs through the whole loop.
Testing the helper on a few numbers like this is a good habit whenever a problem is split into helper and caller: if the helper is right, a mistake in the result must be in the counting loop, and the other way round.
Complexity
For one number n, isPrime does at most n - 2 remainder checks: a prime goes through the whole loop, while a number with a small divisor stops early. With values up to 100000, a prime near that size takes about 100000 checks, and an array of such values multiplies that by its length. That is fine for these inputs. Stopping the loop at the square root of n would be faster, because a composite number always has a divisor that is at most its square root, but this lesson keeps the simpler test.
Space: O(1), since only a few numbers are stored.
Edge cases and common mistakes
- 0 and 1. They return
falsefrom the first check. Without it, the loop would not run for 1, and 1 would be reported as prime. - 2. The loop starts at 2 and needs
d < 2, so it doesn't run, and 2 is correctly prime.countPrimes([2])returns 1. - Repeats.
[7, 10, 7]returns 2, because each 7 is counted. - Loop bound. Using
d <= nwould testn % n, which is always 0, and no number would be prime. - Starting at 1. Every number is divisible by 1, so a loop starting there would reject everything.
- Returning inside the counting loop. That would stop after the first number.
Testing
[2, 3, 4, 5, 6]gives3.[0, 1, 9]gives0.[7, 10, 7]gives2.[2]gives1.[99991]gives1, since 99991 is prime.
