
Problem
Solution
Submissions
Check if Number is Prime
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to determine if a given positive integer is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, etc.
Example 1
- Input: num = 17
- Output: true
- Explanation:
- Check if 17 is greater than 1 (it is).
- Check if 17 is divisible by any number from 2 to √17 (approximately 4.12).
- Test divisibility: 17 % 2 = 1, 17 % 3 = 2, 17 % 4 = 1.
- None of these divisions result in 0, so 17 has no divisors other than 1 and itself.
- Therefore, 17 is a prime number.
- Check if 17 is greater than 1 (it is).
Example 2
- Input: num = 15
- Output: false
- Explanation:
- Check if 15 is greater than 1 (it is).
- Check if 15 is divisible by any number from 2 to √15 (approximately 3.87).
- Test divisibility: 15 % 2 = 1, 15 % 3 = 0.
- Since 15 % 3 = 0, we found that 15 is divisible by 3.
- Therefore, 15 is not a prime number.
- Check if 15 is greater than 1 (it is).
Constraints
- 1 ≤ num ≤ 10^6
- The input will always be a positive integer
- Numbers less than or equal to 1 should return false
- Time Complexity: O(√n) where n is the input number
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Handle edge cases first: numbers less than or equal to 1 are not prime
- Check if the number is 2, which is the only even prime number
- If the number is even and greater than 2, it's not prime
- For odd numbers, check divisibility from 3 up to the square root of the number
- Only check odd divisors to optimize the algorithm
- If any divisor is found, the number is not prime
- If no divisors are found, the number is prime