483.Check if a Number Is Prime
Easy
Given a non-negative integer
n, return whether it's a prime number — a number greater than 1 with no positive divisors other than 1 and itself.
Both solutions share the same n < 2 shortcut; they only differ in how far the trial divisionTrial DivisionTesting candidate divisors one at a time with the modulo operator — any exact division means the number isn't prime. search needs to go. Checking every candidate up to n − 1 is the direct reading of the definition. Checking only up to √nSquare Root BoundAny factor pair of n has one factor ≤ √n and one ≥ √n — so if no divisor exists up to √n, none exists at all. relies on a simple fact about factor pairs to rule out the same composite numbers in dramatically fewer steps, especially for large n.
Example 1:
Input: n = 7
Output: true
Example 2:
Input: n = 10
Output: false
Example 3:
Input: n = 1
Output: false
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 1000000
n =
7