Article start
DSA Course: Interview Patterns and Problem Solving
Module 15: Math & Number Theory

Prime Check: Square Root Trial Division Pattern

Check primality by testing only necessary factors up to square root of n.

May 29, 2026·23

Learning Outcome

After this lesson, you should be able to prove why a composite number must have a factor at or below square root of n.

Problem Statement

Given an integer n, return true if n is prime and false otherwise.

InputOutputWhy
n = 29true29 has no divisor from 2 through 5, so it is prime.

Brute Force Approach

Try every divisor from 2 to n

    1. This is easy to understand but wastes many checks.

Optimized Approach

Handle small numbers first, reject multiples of 2 and 3, then test candidates of the form 6k

  • 1 and 6k + 1 while i * i is at most n.

Exact Pseudocode

if n < 2:
  return false
if n is 2 or 3:
  return true
if n is divisible by 2 or 3:
  return false
i = 5
while i * i <= n:
  if n is divisible by i or i + 2:
    return false
  i += 6
return true

Reference Code

class Solution:
    def isPrime(self, n):
        if n < 2:
            return False
        if n == 2 or n == 3:
            return True
        if n % 2 == 0 or n % 3 == 0:
            return False

        i = 5
        while i * i <= n:
            if n % i == 0 or n % (i + 2) == 0:
                return False
            i += 6
        return True

Sample Dry Run

StepStateResult
Small checks29 is greater than 3 and not divisible by 2 or 3continue
i = 5

5

  • 5 is at most 29
test 5 and 7
No divisor29 % 5 and 29 % 7 are nonzeromove ahead
Stop

next i is 11, and 11

  • 11 is greater than 29
true

Complexity

MeasureValueReason
TimeO(sqrt(n))Only possible factors up to square root of n are checked.
SpaceO(1)No extra data structure is used.

Edge Cases

  • n less than 2 is not prime.
  • 2 and 3 are prime.
  • Perfect squares like 49 must be caught, so use i * i at most n.

Interview Checklist

  • Handle small values before the loop.
  • Reject even numbers and multiples of 3 early.
  • Test 6k

    • 1 and 6k + 1 candidates only.

FAQs

Why check only up to square root of n?

If both factors were larger than square root of n, their product would be larger than n.

Why use 6k plus or minus 1?

Every prime greater than 3 is beside a multiple of 6, so other candidates can be skipped.

What is the core pattern?

Square-root trial division.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.