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 TheoryA 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
- If the number is less than 2, it's not prime.
- If the number is 2 or 3, it is prime.
- Check if the number is divisible by 2 or 3; if so, it's not prime (handles the two smallest prime factors quickly).
- 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.
- 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.
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 TrueBehind 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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.