VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-for-prime-number/

⇱ Check for Prime Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for Prime Number

Last Updated : 1 Apr, 2026

Given a number n, check whether it is a prime number or not.
Note: A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.

Input:n = 7
Output:true
Explanation: 7 is a prime number because it is greater than 1 and has no divisors other than 1 and itself.

Input:n = 25
Output:false
Explanation: 25 is not a prime number because it is divisible by 5 (25 = 5 × 5), so it has divisors other than 1 and itself.

Input: n = 1
Output: false
Explanation: 1 has only one divisor (1 itself), which is not sufficient for it to be considered prime.

[Naive Approach] Basic Trial Division - O(n) Time and O(1) Space

To check if a number n is prime, first see if it's less than 2 — if so, it's not prime. Otherwise, try dividing n by every number from 2 to n - 1. If any number divides it evenly, then n is not prime. If none do, then n is a prime number.


Output
true

[Better Approach] Square Root Trial Division - O(√n) time and O(1) space

The idea is that we only need to check divisors up to √n (i.e., while i * i <= n) because divisors always come in pairs - one smaller and one larger. If a larger divisor exists beyond √n, its smaller paired divisor would have already been checked, making further checks unnecessary.

Every number n can be written as a product of two numbers: n=a×b. Here, a and b are divisors of n.

Example: n = 36

  • 36 = 2 × 18 - pair (2,18)
  • 36 = 3 × 12 - pair (3,12)
  • 36 = 4 × 9 - pair (4,9)
  • 36 = 6 × 6 - pair (6,6)

Why does this work?

Consider a number n with a pair of factors (a, b) such that a × b = n.

  • If a < b, then a × a < a × b = n, which means a < √n.
  • This shows that any factor larger than √n must have a corresponding factor smaller than or equal to √n.
  • Therefore, it is enough to check numbers up to √n.
  • If no factor ≤ √n is found, n is prime.

Output
true

[Expected Approach] Optimized Square Root Trial Division - O(√n) Time and O(1) Space

Numbers that are divisible by 2 or 3 are not prime, so we can skip them entirely. To check whether a number is prime, it is sufficient to test only the numbers of the form 6k ± 1 up to √n.

Why all prime greater than 3 can be expressed in the form 6k ± 1?

  • The forms 6k, 6k+2 and 6k + 4 are all even and greater than, so they are composite. The form is a multiple of and greater than , so it is composite.
  • The form 6K + 3 is a multiple of 3
  • The only remaining forms are 6k + 1 and 6K + 5. The form 6K + 5 can can be rewritten as 6(k + 1) - 1, so it is covered under (6k - 1) for k = k + 1.

Output
true

Sieve Algorithms for Prime Number Generation

Prime Number Algorithms and Related Problems

Some Other Primality Testing Methods

Comment