Xerobit
Dev Productivity

How to Check if a Number Is Prime: By Hand and in Code

Check if a number is prime by dividing by primes up to its square root. Worked examples for 91, 77 and 797, plus tested Python and JavaScript code and Miller-Rabin.

MA Mian Ali Khalid 9 min read
Free tool
Prime Number Checker
Test if a number is prime, see its prime factorization, or list all primes up to a limit.
Open tool →
On this page ⌄
  1. By hand
  2. In Python
  3. In JavaScript
  4. When trial division stops being enough
  5. Common mistakes
  6. Tested
  7. Sources

To check if a number is prime, divide it by every prime up to its square root. If none of them divides it evenly, the number is prime. If one does, the number is composite and that divisor is a factor. For 91 the square root is about 9.5, and 91 = 7 x 13, so 91 is not prime. For 797 the square root is about 28.2 and no prime up to 28 divides it, so 797 is prime.

That is enough for numbers you check by hand and for anything up to roughly 10^12 in code. Beyond that, Miller-Rabin with a proven set of bases is the practical choice. This guide covers both, with code that was run and compared against SymPy. To skip the arithmetic, the online prime checker returns the verdict and the smallest factor.

By hand

Take the number n and follow four steps.

  1. If n is 1 or less, it is not prime. If n is 2 or 3, it is prime.
  2. If n is even, it is not prime (unless it is 2).
  3. Find the whole-number part of the square root of n. You only need to test primes up to that value.
  4. Divide n by each of those primes in turn. One exact division means composite. No exact division means prime.

Divisibility rules for 2, 3, 5, 7 and 11

These rules save you from long division. Each is a shortcut for "is the remainder 0?".

PrimeRule9177797
2Last digit is even1, no7, no7, no
3Digit sum divisible by 39 + 1 = 10, no7 + 7 = 14, no7 + 9 + 7 = 23, no
5Last digit is 0 or 5nonono
7Double the last digit, subtract it from the rest, repeat; the result is divisible by 7 (or 0)9 - 2 = 7, yes7 - 14 = -7, yes79 - 14 = 65, no
11Alternating digit sum divisible by 119 - 1 = 8, no7 - 7 = 0, yes7 - 9 + 7 = 5, no

Why 91 is not prime

The square root of 91 is about 9.54, so test 2, 3, 5 and 7. The first three leave remainder 1 each. Seven divides it: 91 = 7 x 13. Many people stop at 2, 3 and 5 and call 91 prime because it looks prime. The rule for 7 catches it.

Why 77 is not prime

The square root of 77 is about 8.77, so test 2, 3, 5 and 7. Seven divides it: 77 = 7 x 11. The rule for 11 agrees (7 - 7 = 0).

Is 797 a prime number?

Yes. The square root of 797 is about 28.2, so the primes to test are 2, 3, 5, 7, 11, 13, 17, 19 and 23. The remainders are 1, 2, 2, 6, 5, 4, 15, 18 and 15. None is 0, so 797 is prime.

Why the square root is enough

Suppose n = a x b with 1 < a <= b. If a were larger than the square root of n, then b would be too, and a x b would exceed n. So the smaller factor a is at most the square root of n. Any composite number therefore has a factor from 2 up to its square root, and if you find none there, none exists. You also only need prime divisors: if a composite divisor works, its prime factors divide n as well.

In Python

Three implementations were written and run. The first is trial division by 2 and then odd numbers. The second is the 6k +/- 1 wheel: after ruling out 2 and 3, every remaining prime is one more or one less than a multiple of 6, so only a third of all numbers are tested instead of half. The third is deterministic Miller-Rabin, described in the next section.

from math import isqrt

def trial_division(n):
    if n < 2:
        return False
    if n < 4:
        return True
    if n % 2 == 0:
        return False
    d = 3
    r = isqrt(n)
    while d <= r:
        if n % d == 0:
            return False
        d += 2
    return True

def wheel_6k(n):
    if n < 2:
        return False
    if n < 4:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    r = isqrt(n)
    d = 5
    while d <= r:
        if n % d == 0 or n % (d + 2) == 0:
            return False
        d += 6
    return True

The Miller-Rabin function, with the witness set it uses:

BASES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)

def miller_rabin(n):
    if n < 2:
        return False
    for p in BASES:
        if n % p == 0:
            return n == p
    d = n - 1
    s = 0
    while d % 2 == 0:
        d //= 2
        s += 1
    for a in BASES:
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True

math.isqrt has been in the standard library since Python 3.8 and returns an exact integer square root, so there is no floating-point rounding at the boundary. Avoid int(n ** 0.5) for large n, because a float cannot represent every integer above 2^53.

Results for the worked examples:

91 {'trial_division': False, 'wheel_6k': False, 'miller_rabin': False} sympy False
77 {'trial_division': False, 'wheel_6k': False, 'miller_rabin': False} sympy False
797 {'trial_division': True, 'wheel_6k': True, 'miller_rabin': True} sympy True
1 {'trial_division': False, 'wheel_6k': False, 'miller_rabin': False} sympy False
2 {'trial_division': True, 'wheel_6k': True, 'miller_rabin': True} sympy True

In JavaScript

The same three functions in Node. Trial division and the wheel use ordinary numbers, so they are only safe up to 2^53 - 1 (Number.MAX_SAFE_INTEGER). Miller-Rabin uses BigInt because the intermediate products overflow 64 bits.

export function trialDivision(n) {
  if (n < 2) return false;
  if (n < 4) return true;
  if (n % 2 === 0) return false;
  const r = Math.floor(Math.sqrt(n));
  for (let d = 3; d <= r; d += 2) if (n % d === 0) return false;
  return true;
}

export function wheel6k(n) {
  if (n < 2) return false;
  if (n < 4) return true;
  if (n % 2 === 0 || n % 3 === 0) return false;
  const r = Math.floor(Math.sqrt(n));
  for (let d = 5; d <= r; d += 6) if (n % d === 0 || n % (d + 2) === 0) return false;
  return true;
}

const BASES = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n];

function powMod(b, e, m) {
  let r = 1n;
  b %= m;
  while (e > 0n) {
    if (e & 1n) r = (r * b) % m;
    b = (b * b) % m;
    e >>= 1n;
  }
  return r;
}

export function millerRabin(nIn) {
  const n = BigInt(nIn);
  if (n < 2n) return false;
  for (const p of BASES) if (n % p === 0n) return n === p;
  let d = n - 1n, s = 0;
  while ((d & 1n) === 0n) { d >>= 1n; s++; }
  for (const a of BASES) {
    let x = powMod(a, d, n);
    if (x === 1n || x === n - 1n) continue;
    let composite = true;
    for (let i = 0; i < s - 1; i++) {
      x = (x * x) % n;
      if (x === n - 1n) { composite = false; break; }
    }
    if (composite) return false;
  }
  return true;
}

Output for the worked examples (trial division, wheel, Miller-Rabin):

91 false false false
77 false false false
797 true true true
1 false false false
2 true true true

When trial division stops being enough

Trial division needs up to the square root of n divisions, so the work grows with the square root of the number. Doubling the number of digits squares the cost. Miller-Rabin does a few modular exponentiations instead, and their cost grows with the number of digits.

The times below are the best of several runs for a prime near each size (999983, 999999999989 and 999999999999999989), on an Intel64 Family 6 Model 165 CPU with Python 3.11.15 and Node 25.8.0. Treat the absolute numbers as machine-specific and the ratios as the lesson.

Prime testedPython trial divisionPython 6k +/- 1Python Miller-RabinNode trial divisionNode 6k +/- 1Node Miller-Rabin (BigInt)
near 10^684 microseconds53 microseconds39 microseconds5 microseconds3 microseconds66 microseconds
near 10^1293.7 ms70.2 ms0.124 ms5.5 ms3.7 ms0.085 ms
near 10^18not runnot run0.251 msnot runnot run0.134 ms

Three things stand out. The 6k +/- 1 wheel is only about 1.3 to 1.6 times faster than odd-only trial division, not a different order of magnitude. At 10^12 Miller-Rabin is hundreds of times faster than trial division in Python (roughly 550 to 750 times across runs) and tens of times faster in Node (roughly 45 to 65 times). And near 10^6 plain division wins in Node, because BigInt arithmetic costs more than a few hundred small divisions. Trial division at 10^18 was not timed: it needs about 5 x 10^8 odd divisors, roughly 1,000 times the 10^12 work.

Which Miller-Rabin bases are safe for 64-bit numbers

Miller-Rabin tests a number against chosen bases a. A composite that passes for a given base is a strong pseudoprime to that base. A fixed list of bases is a proof, not a guess, only when no composite below your limit passes all of them. The Wikipedia article on the Miller-Rabin primality test lists the first twelve primes (2 through 37) as sufficient for every n below 2^64 (18,446,744,073,709,551,616), based on Feitsma and Galway's enumeration of base-2 pseudoprimes. OEIS A014233 agrees: the smallest odd composite that is a strong pseudoprime to the first 12 prime bases is 318,665,857,834,031,151,167,461, far above 2^64, while for the first 11 prime bases it is 3,825,123,056,546,413,051, which is below 2^64. That is why the code uses all twelve.

A shorter list covers a smaller range. Bases 2, 3, 5 and 7 are enough below 3,215,031,751, and 3,215,031,751 = 151 x 751 x 28351 is the first composite those four bases miss. Run with bases 2, 3, 5, 7 only it passes; adding 11 rejects it:

3215031751 passes bases 2,3,5,7: True | with 11 added: False | factors [151, 751, 28351]

A plain Fermat test is weaker still: 561 = 3 x 11 x 17 is a Carmichael number, and pow(2, 560, 561) returns 1, so a Fermat test with base 2 calls it prime.

Cross-checks

Each function was compared with SymPy isprime (SymPy 1.14.0). The Node versions were compared with an independent sieve of Eratosthenes and with SymPy-generated vectors.

CheckResult
Python, all n from 0 to 999,999, three functions vs SymPy0 mismatches
Node, all n from 0 to 999,999, three functions vs a sieve0 mismatches
Python Miller-Rabin vs SymPy, 10,000 random odd 64-bit numbers (480 were prime)0 mismatches
Python Miller-Rabin, 2,000 products of two random 32-bit primes plus the primes themselves0 failures
Node Miller-Rabin vs SymPy-generated vectors (11,007: random 64-bit, semiprimes, traps)0 mismatches
Traps: 561, 41041, 2047, 1,373,653, 25,326,001, 2,152,302,898,747, 3,474,749,660,383, 3,215,031,751, 341,550,071,728,321, 3,825,123,056,546,413,051all composite, all rejected
2^61 - 1 = 2,305,843,009,213,693,951prime, accepted
Largest prime below 2^64: 18,446,744,073,709,551,557prime, accepted

Numbers above 2^64 are outside what this witness set proves. For those, use a library that adds a Lucas test rather than extending the base list by hand.

Common mistakes

  • Calling 1 prime. A prime has exactly two distinct divisors, 1 and itself. The number 1 has only one, so it is not prime. The code returns False for 1.
  • Forgetting that 2 is prime. 2 is the only even prime. Every other even number is divisible by 2, so skipping evens after handling 2 is correct, but the function must still return True for 2 itself.
  • Stopping at the wrong bound. Testing only up to n / 2 is correct but wasteful. Stopping before the square root is wrong: for 49 you must test 7, so the loop includes the square root itself (d <= r, not d < r).
  • Using floating-point square roots on big integers. math.sqrt in Python and Math.sqrt in JavaScript round for values above 2^53. Use math.isqrt or BigInt.
  • Trusting numbers that look prime. 91 (7 x 13), 119 (7 x 17) and 221 (13 x 17) all pass the checks for 2, 3 and 5. Test every prime up to the square root.
  • Trusting a short base list. Bases 2, 3, 5, 7 miss 3,215,031,751. Use the twelve-base set for 64-bit inputs.

Tested

  • Python 3.11.15 and Node 25.8.0 on Windows 11, Intel64 Family 6 Model 165 CPU, run on 2026-11-17.
  • SymPy 1.14.0 as the reference for Python and for the Node test vectors; a sieve of Eratosthenes for Node below 1,000,000.
  • Not tested: numbers above 2^64, other languages, and the timing table on other hardware. Trial division at 10^18 was not run.

Sources

  • Wikipedia, Miller-Rabin primality test: witness sets for n < 2^64 and n < 3,215,031,751, fetched 2026-11-17.
  • OEIS, A014233: smallest strong pseudoprimes to the first n prime bases, fetched 2026-11-17.
  • Wikipedia, Primality test: trial division and the 6k +/- 1 optimisation, fetched 2026-11-17.
  • Python documentation, math.isqrt: added in version 3.8.
  • SymPy documentation, number theory module: isprime, used as the reference.

Related tools

Written by Mian Ali Khalid. More guides in Dev Productivity.