Step 2: Filtering Prime Numbers
With our candidates ready, we must now filter them to identify the prime numbers.
The Naive Approach
We could manually check each number by looping through every number from 2
up to the current one, verifying if the current number is divisible by any other number. If it's divisible, it's not a prime number!
Here's a simple implementation:
1function isPrime(num) {
2 for (let i = 2; i < num; i++) {
3 if (num % i === 0) return false;
4 }
5 return num > 1;
6}
7
8console.log(isPrime(7));
Efficiency Considerations
While this naive approach works, it's pretty slow. The manual check is an O(n)
operation, and since we need to run it for each number less than the input n
, the overall function has a time complexity of O(n^2)
.
Can we improve this? Stay tuned, and we'll explore more efficient ways to identify prime numbers in our next lessons!
xxxxxxxxxx
function isPrime(num) {
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return num > 1;
}
​
console.log(isPrime(7));
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment