JavaScript Program to Check Prime Number
function isPrime(num) { if (num <= 1) return false; for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) return false; } return true; } to check if a number is prime.Examples
How to Think About It
Algorithm
Code
function isPrime(num) { if (num <= 1) return false; for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) return false; } return true; } console.log(isPrime(2)); // true console.log(isPrime(15)); // false console.log(isPrime(17)); // true
Dry Run
Let's trace the number 15 through the code to see if it is prime.
Check if number is <= 1
15 is greater than 1, so continue.
Start loop from 2 to sqrt(15)
sqrt(15) is about 3.87, so loop i = 2 to 3.
Check divisibility by 2
15 % 2 = 1 (not zero), continue.
Check divisibility by 3
15 % 3 = 0 (zero), so return false.
| i | num % i | Is num divisible? |
|---|---|---|
| 2 | 1 | No |
| 3 | 0 | Yes - Not prime |
Why This Works
Step 1: Exclude numbers less than or equal to 1
Numbers 1 and below are not prime by definition, so we return false immediately.
Step 2: Loop only up to square root
Checking divisors beyond the square root is unnecessary because any larger factor pairs with a smaller one already checked.
Step 3: Return true if no divisors found
If no number divides evenly, the number is prime, so we return true.
Alternative Approaches
function isPrime(num) { if (num <= 1) return false; for (let i = 2; i < num; i++) { if (num % i === 0) return false; } return true; } console.log(isPrime(17));
function isPrime(num, i = 2) { if (num <= 1) return false; if (i > Math.sqrt(num)) return true; if (num % i === 0) return false; return isPrime(num, i + 1); } console.log(isPrime(17));
Complexity: O(√n) time, O(1) space
Time Complexity
The loop runs up to the square root of the input number, so the time grows roughly with √n.
Space Complexity
The program uses a fixed amount of extra space regardless of input size, so space is O(1).
Which Approach is Fastest?
Checking up to the square root is faster than checking all numbers up to n-1. Recursive methods add overhead and are less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check up to sqrt(n) | O(√n) | O(1) | Efficient and simple |
| Check up to n-1 | O(n) | O(1) | Simple but slow |
| Recursive check | O(√n) | O(√n) | Elegant but uses more space |