Prime Number Checker - Problem

Given a positive integer n, determine whether it is a prime number.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Examples:

  • 2, 3, 5, 7, 11 are prime numbers
  • 4, 6, 8, 9, 10 are not prime numbers

Optimize your solution by checking only up to the square root of n.

Input & Output

Example 1 — Small Prime Number
$ Input: n = 17
Output: true
💡 Note: 17 is a prime number. We only need to check divisors from 2 to √17 ≈ 4. None of 2, 3, or 4 divide 17 evenly, so it's prime.
Example 2 — Composite Number
$ Input: n = 15
Output: false
💡 Note: 15 is not prime because it can be divided by 3 (15 ÷ 3 = 5) and 5 (15 ÷ 5 = 3). We find the divisor 3 when checking up to √15 ≈ 3.87.
Example 3 — Edge Case Small Number
$ Input: n = 2
Output: true
💡 Note: 2 is the smallest prime number. It's only divisible by 1 and itself.

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
INPUTALGORITHMRESULT17Number to checkIs 17 prime?Need to find if it hasany divisors besides1 and itself1Calculate √17 ≈ 42Check divisors: 2, 3, 4317÷2=8.5, 17÷3=5.67417÷4=4.25 (no exact)No divisors found!Therefore 17 is primetrue17 is primeChecked only 3 divisors(instead of 15) thanksto √n optimizationEfficient: O(√n)Key Insight:Divisors come in pairs - if one exists above √n, its pair must be below √nTutorialsPoint - Prime Number Checker | Square Root Optimization
Asked in
Google 12 Microsoft 8 Amazon 15
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen