Check if Number is Prime in DSA Javascript - Time & Space Complexity
We want to understand how the time to check if a number is prime grows as the number gets bigger.
Specifically, how many steps does it take to decide if a number has no divisors other than 1 and itself?
Analyze the time complexity of the following code snippet.
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return true;
}
This code checks if a number is prime by testing all numbers from 2 up to one less than the number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that checks divisibility from 2 to num - 1.
- How many times: Up to num - 2 times in the worst case.
As the number gets bigger, the loop runs more times, almost as many as the number itself.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 8 checks |
| 100 | Up to 98 checks |
| 1000 | Up to 998 checks |
Pattern observation: The number of checks grows roughly in a straight line with the input size.
Time Complexity: O(n)
This means the time to check if a number is prime grows directly with the size of the number.
[X] Wrong: "Checking divisibility up to the number itself is necessary."
[OK] Correct: You only need to check up to the square root of the number because if a larger factor exists, a smaller one must exist too.
Understanding this time complexity helps you explain how to improve prime checks and shows you can analyze simple loops well.
"What if we only check divisibility up to the square root of the number? How would the time complexity change?"
Practice
prime?Solution
Step 1: Understand the definition of prime number
A prime number is a number greater than 1 that has no divisors other than 1 and itself.Step 2: Compare options with definition
It has exactly two distinct positive divisors: 1 and itself. matches the definition exactly. Other options describe incorrect properties.Final Answer:
It has exactly two distinct positive divisors: 1 and itself. -> Option AQuick Check:
Prime number = two divisors only [OK]
- Thinking all even numbers are prime
- Confusing prime with numbers ending in 5
- Assuming prime numbers have many divisors
n is prime?Solution
Step 1: Analyze the loop range for checking divisors
We check divisors from 2 up to but not including n to find if n is divisible by any number other than 1 and itself.Step 2: Evaluate each option's loop and condition
for(let i = 2; i < n; i++) { if(n % i === 0) return false; } return true; correctly loops from 2 to n-1 and returns false if divisible. for(let i = 2; i <= n; i++) { if(n % i === 0) return false; } return true; incorrectly includes n itself, always returning false. for(let i = 1; i < n; i++) { if(n % i === 0) return false; } return true; starts from 1, which divides all numbers. for(let i = 2; i < n; i++) { if(n % i !== 0) return false; } return true; returns false if not divisible, which is wrong logic.Final Answer:
for(let i = 2; i < n; i++) { if(n % i === 0) return false; } return true; -> Option AQuick Check:
Loop from 2 to n-1 and check divisibility [OK]
- Including n in divisor check
- Starting loop from 1
- Using wrong condition for divisibility
function isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
console.log(isPrime(29));Solution
Step 1: Understand the prime check logic with square root optimization
The function returns false if n is less than or equal to 1. Then it checks divisors from 2 up to square root of n. If any divisor divides n, it returns false; otherwise true.Step 2: Trace the function call with n = 29
29 > 1, loop runs i from 2 to 5 (since sqrt(29) ≈ 5.38). None of 2,3,4,5 divides 29 evenly, so loop completes and returns true.Final Answer:
true -> Option BQuick Check:
29 is prime, function returns true [OK]
- Looping up to n instead of sqrt(n)
- Not handling n <= 1 case
- Returning wrong boolean values
num is prime:function checkPrime(num) {
if (num < 2) return false;
for (let i = 2; i < num / 2; i++) {
if (num % i === 0) return false;
}
return true;
}Solution
Step 1: Identify the logic error by tracing with num=4
For num=4 (not prime), if(4 < 2) false; for(let i=2; i < 4/2; i++) i.e. i < 2 false, loop skips, returns true incorrectly.Step 2: Determine the cause and fix
The i < num/2 fails when num/2 is integer equal to starting i (e.g., num=4), skipping the check. Use i <= num/2 to include boundary. Loop should run until i <= num / 2, not i < num / 2. identifies this error; B offers further efficiency.Final Answer:
Loop should run until i <= num / 2, not i < num / 2. -> Option DQuick Check:
For num=4, i <= num/2 checks i=2 [OK]
- Using i < num/2 which skips checks for composites like 4
- Incorrect boundary conditions in loop
- Wrong base case for numbers less than 2
max. Which approach is best to optimize performance?Solution
Step 1: Understand the problem of finding primes up to max
We need to test each number from 2 to max to see if it is prime efficiently.Step 2: Evaluate each approach for efficiency
Check each number from 2 to max using a loop up to sqrt of that number to test primality. uses the efficient method of checking divisibility only up to sqrt of each number, reducing unnecessary checks. Options B and C check more divisors than needed, causing slower performance. Return all numbers from 2 to max without any checks. ignores primality checks.Final Answer:
Check each number from 2 to max using a loop up to sqrt of that number to test primality. -> Option CQuick Check:
Use sqrt limit for divisor checks to optimize prime search [OK]
- Checking divisors up to number itself
- Ignoring efficiency in prime checking
- Returning all numbers without checks
Ready to prove it?
Pass the test and this pattern moves unknown
