Algorithms · Visualized

Number Theory: Prime Check

Number Theory

Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.

A number is prime if it's greater than 1 and has no divisors other than 1 and itself. Time: O(√n) average, O(√n) worst; space: O(1).

Big-O: GCD O(log min(a,b)); sieve O(n log log n).

Prime Check

Number Theory

A number is prime if it's greater than 1 and has no divisors other than 1 and itself. To check efficiently, you only need to test potential divisors up to the square root of the number — because if a number has a divisor larger than its square root, it must also have a matching divisor smaller than the square root.

How Prime Check Works

  1. If the number is less than 2, it's not prime.
  2. If the number is 2 or 3, it is prime.
  3. Check if the number is divisible by 2 or 3; if so, it's not prime (handles the two smallest prime factors quickly).
  4. Loop a potential divisor from 5 up to the square root of the number, checking divisibility by the divisor and the divisor+2 each time (this skips multiples of 2 and 3 efficiently), incrementing by 6 each loop.
  5. If no divisor evenly divides the number throughout this loop, the number is prime.

Prime Check Worked Example

Input: 29

29 is not divisible by 2 or 3. Check divisors up to √29≈5.4: try 5 → 29/5 is not whole. No more divisors to check (next would be 7, past √29). No divisors found — 29 is prime.

Number Theory: Prime CheckO(√n)
Test divisors up to √n.
Press ▶ Run to visualize this algorithm.
Step 1 / 6
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Check if 29 is prime: test divisors up to √29 ≈ 5.
Python · Number Theory in Code
import math

def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(math.isqrt(n)) + 1):
        if n % d == 0:
            return False
    return True

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Prime Check Time & Space Complexity

BestO(1) — small numbers like 2, 3
AverageO(√n)
WorstO(√n)
SpaceO(1)

When to Use Prime Check

  • Cryptography (RSA key generation relies on large prime checks), hashing, and load-balancing (prime-sized hash tables reduce collisions).

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.