Prime Number Checker
This challenge asks you to implement a function that determines whether a given integer is a prime number. Prime numbers are fundamental in number theory and cryptography, making this a foundational problem for many advanced algorithms.
Problem Description
You need to create a JavaScript function named isPrime that accepts a single integer argument, num. The function should return true if num is a prime number, and false otherwise.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Key Requirements:
- The function must correctly identify prime numbers.
- The function should handle various input values, including edge cases.
Expected Behavior:
- For any input
numthat is prime,isPrime(num)should returntrue. - For any input
numthat is not prime,isPrime(num)should returnfalse.
Edge Cases to Consider:
- Numbers less than or equal to 1.
- The number 2.
- Even numbers greater than 2.
- Large numbers.
Examples
Example 1:
Input: 7
Output: true
Explanation: 7 is a prime number because its only positive divisors are 1 and 7.
Example 2:
Input: 10
Output: false
Explanation: 10 is not a prime number because it is divisible by 2 and 5 (in addition to 1 and 10).
Example 3:
Input: 1
Output: false
Explanation: By definition, prime numbers must be greater than 1.
Example 4:
Input: 2
Output: true
Explanation: 2 is the smallest prime number and the only even prime number.
Constraints
- The input
numwill be an integer. numwill be within the range of typical JavaScript number representation (e.g.,-Number.MAX_SAFE_INTEGERtoNumber.MAX_SAFE_INTEGER).- Your solution should aim for reasonable performance, especially for larger inputs. A naive approach iterating up to
nummight be too slow for very large numbers.
Notes
- Remember the definition of a prime number: a natural number greater than 1 that has no positive divisors other than 1 and itself.
- Consider how you can optimize your checks. For instance, do you need to check every number up to
numas a potential divisor? - Think about the properties of even numbers and their divisibility.