Check if a Number is Prime
Given a positive integer n, determine whether it is a prime number. A prime number is any integer greater than 1 that has no positive divisors other than 1…
Given a positive integer `n`, determine whether it is a prime number. A prime number is any integer greater than 1 that has no positive divisors other than 1 and itself. Return `true` if `n` is prime, and `false` otherwise. **Note:** 1 is not considered a prime number by definition.
- `1 ≤ n ≤ 10^6` - `n` is always a positive integer.
Example 1: input n = 11; output true. 11 has no divisors other than 1 and 11 itself. Checking candidates 2 through 3 (√11 ≈ 3.31) reveals no factor, confirming 11 is prime.
Example 2: input n = 21; output false. 21 = 3 × 7, so it has a divisor other than 1 and itself. The check finds 3 divides 21 with no remainder at the first odd candidate tested.
Example 3: input n = 2; output true. 2 is the smallest prime number. The only even prime — the even-check early exit must not incorrectly exclude it.
Category: Math. Topic: math. Difficulty: Easy. Patterns: math.