Check for Prime Number (JavaScript)
Check for Prime Number
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Checking if a number is prime is a fundamental problem in number theory and programming.
Understanding the Concept
To determine if a number N
is prime, we need to check if it’s divisible by any integer from 2 up to N-1
. If it is, it’s not prime. If it’s not divisible by any of these numbers, it is prime.
Key Considerations and Optimizations
- Numbers less than or equal to 1 are not prime.
- 2 is the only even prime number.
- Any even number greater than 2 is not prime.
- We only need to check for divisors up to the square root of
N
. IfN
has a divisor greater than its square root, it must also have a divisor smaller than its square root.
Common Approaches
1. Basic Trial Division:
Checks divisibility from 2 up to num - 1
.
Copy to Clipboard
Explanation:
- Handles base case for numbers
<= 1
. - Loops from 2 up to `num - 1`. If any `i` divides `num` evenly, it's not prime.
2. Optimized Trial Division (Up to Square Root):
This is a significant optimization, as we only need to check for divisors up to the square root of the number.
Copy to Clipboard
Explanation:
- Handles small prime numbers (2, 3) and immediate non-primes (multiples of 2 and 3).
- The loop checks `i` and `i + 2` because all primes greater than 3 can be written in the form
6k ± 1
. This skips checking multiples of 2 and 3. - The loop condition `i * i <= num` (or `i <= Math.sqrt(num)`) is crucial for efficiency.
Key Takeaways
- Definition of Prime: A number divisible only by 1 and itself (and greater than 1).
- Optimizations: Checking up to the square root and skipping even numbers/multiples of 3 significantly improves performance.
- Efficiency: For very large numbers, more advanced primality tests (like Miller-Rabin) are used, but for typical programming challenges, optimized trial division is sufficient.