{
  "id": "miller-rabin-primality-test",
  "title": "Miller–Rabin Primality Test",
  "lang": "en",
  "source_lang": "en",
  "summary": "The Miller–Rabin primality test is an efficient randomized algorithm that detects composite integers with certainty and identifies probable primes with a controllably small error probability.",
  "category": "mathematics",
  "subcategory": "algebra",
  "type": "concept",
  "aliases": [
    "Miller–Rabin test",
    "Rabin–Miller primality test",
    "strong probable-prime test"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/miller-rabin-primality-test/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/miller-rabin-primality-test/",
      "json": "https://aiwiki.page/zh/miller-rabin-primality-test.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The Miller–Rabin primality test is a primality-testing algorithm that determines whether an integer is composite or is a probable prime. It applies necessary conditions for primality to a sequence of modular powers. A failed condition proves that the input is composite; passing the test does not, by itself, prove that it is a prime number. For any fixed odd composite input, one independently and uniformly chosen test base has a probability of less than or equal to \\(1/4\\) of failing to expose its compositeness. Repeating the test with independent random bases reduces this error bound exponentially.\n\nThe test is widely used in computational number theory and cryptographic prime generation because it is fast, straightforward to implement, and effective on very large integers."
    },
    {
      "heading": "Mathematical basis",
      "text": "Let \\(n>2\\) be an odd integer. Write\n\n\\[n-1=2^s d,\\]\n\nwhere \\(d\\) is odd and \\(s\\geq 1\\). For a chosen integer base \\(a\\), with \\(2\\leq a\\leq n-2\\), consider the sequence in modular arithmetic\n\n\\[a^d,\\ a^{2d},\\ a^{4d},\\ldots,\\ a^{2^{s-1}d},\\ a^{2^s d} \\pmod n.\\]\n\nEach term after the first is obtained by squaring the preceding term modulo \\(n\\).\n\nIf \\(n\\) is prime, Fermat’s little theorem gives\n\n\\[a^{n-1}\\equiv 1\\pmod n.\\]\n\nMoreover, modulo a prime, the only square roots of \\(1\\) are \\(1\\) and \\(-1\\). This follows because the residue classes form a finite field, in which\n\n\\[x^2-1=(x-1)(x+1)=0\\]\n\nimplies \\(x=1\\) or \\(x=-1\\).\n\nConsequently, if \\(n\\) is prime, either\n\n\\[a^d\\equiv 1\\pmod n,\\]\n\nor\n\n\\[a^{2^r d}\\equiv -1\\pmod n \\qquad \\text{for some }0\\leq r<s.\\]\n\nThese alternatives are the strong probable-prime condition to base \\(a\\). If neither holds, \\(n\\) must be composite.\n\nAn equivalent interpretation starts at the final term, which must be \\(1\\) for a prime, and works backward through the squaring chain. Unless the initial term is already \\(1\\), the chain must reach its first \\(1\\) by squaring \\(-1\\). Reaching \\(1\\) by squaring any other residue reveals behavior impossible modulo a prime."
    },
    {
      "heading": "Algorithm",
      "text": "Inputs below \\(2\\) are not prime. The integers \\(2\\) and \\(3\\) are prime, and any larger even integer is composite. For the remaining odd inputs, the test proceeds as follows.\n\nMillerRabin(n, k):\n    if n < 2:\n        return NOT PRIME\n    if n = 2 or n = 3:\n        return PRIME\n    if n is even:\n        return COMPOSITE\n\n    write n - 1 = 2^s * d with d odd\n\n    repeat k times:\n        choose a uniformly at random from {2, ..., n - 2}\n        x = a^d mod n\n\n        if x = 1 or x = n - 1:\n            continue to the next round\n\n        passed = false\n\n        repeat s - 1 times:\n            x = x^2 mod n\n\n            if x = n - 1:\n                passed = true\n                break\n\n            if x = 1:\n                return COMPOSITE\n\n        if not passed:\n            return COMPOSITE\n\n    return PROBABLY PRIME\n\nHere \\(k\\) is a positive integer specifying the number of rounds. The initial power is computed using modular exponentiation, rather than by constructing the enormous integer \\(a^d\\).\n\nAn optional preliminary greatest common divisor computation can detect a factor immediately: if \\(1<\\gcd(a,n)<n\\), then \\(n\\) is composite. This check is not required for the correctness of the usual algorithm.\n\nTesting divisibility by a small collection of primes before running Miller–Rabin often reduces the total work when screening many candidates."
    },
    {
      "heading": "Witnesses, liars, and strong pseudoprimes",
      "text": "A base that causes the test to reject \\(n\\) is called a strong witness to compositeness, or simply a Miller–Rabin witness. If \\(n\\) is composite but passes for a particular base, that base is a strong liar, and \\(n\\) is a strong pseudoprime to that base.\n\nThese terms describe the relationship between a number and a base. A composite number may pass for one base and fail for another.\n\nExample: detecting a Fermat pseudoprime\n\nConsider\n\n\\[341=11\\cdot31,\\qquad 340=2^2\\cdot85.\\]\n\nFor base \\(2\\),\n\n\\[2^{85}\\equiv32\\pmod{341},\\]\n\nand the next square is\n\n\\[32^2\\equiv1\\pmod{341}.\\]\n\nThe initial value is neither \\(1\\) nor \\(-1\\), and the squaring step reaches \\(1\\) without first reaching \\(-1\\). Miller–Rabin therefore proves that \\(341\\) is composite.\n\nNevertheless,\n\n\\[2^{340}\\equiv1\\pmod{341},\\]\n\nso \\(341\\) passes the simpler Fermat test to base \\(2\\). Miller–Rabin extracts more information from the intermediate powers.\n\nThe nontrivial square root of \\(1\\) also exposes factors:\n\n\\[\\gcd(32-1,341)=31, \\qquad \\gcd(32+1,341)=11.\\]\n\nSuch factor recovery is sometimes possible, although a Miller–Rabin witness need not directly yield a factor.\n\nExample: a passing composite\n\nThe composite integer\n\n\\[2047=23\\cdot89\\]\n\npasses the test to base \\(2\\). Here \\(2046=2\\cdot1023\\), and\n\n\\[2^{1023}\\equiv1\\pmod{2047}.\\]\n\nThus, a single successful round cannot establish primality."
    },
    {
      "heading": "Error guarantee and its interpretation",
      "text": "For every odd composite \\(n>9\\), the number of strong liars among bases \\(1\\leq a\\leq n-1\\) is at most \\((n-1)/4\\). The smaller odd composite \\(9\\) is also easily handled, and the standard sampling interval \\(2\\leq a\\leq n-2\\) gives the familiar per-round error bound of at most \\(1/4\\).\n\nFor a fixed composite input and \\(k\\) independently and uniformly sampled bases,\n\n\\[\\Pr(\\text{all rounds pass}\\mid n\\text{ is composite}) \\leq 4^{-k}.\\]\n\nFor example, \\(64\\) rounds give a worst-case bound of\n\n\\[4^{-64}=2^{-128}.\\]\n\nThe guarantee is one-sided:\n\n- A prime input always passes, assuming correct arithmetic and implementation.\n- A composite input may pass, but its probability of doing so is bounded under the stated sampling assumptions.\n\nIn the terminology of randomized algorithms, Miller–Rabin is a one-sided-error Monte Carlo algorithm.\n\nThe direction of this conditional probability matters. The bound is not automatically the probability that an accepted number is composite:\n\n\\[\\Pr(\\text{composite}\\mid\\text{passes})\\]\n\nalso depends on how candidates were selected and their initial frequency of primality. It is a different quantity from the probability that a fixed composite passes.\n\nThe repetition bound relies on independent, uniform base selection. Repeating the same base gives no additional mathematical assurance, and arbitrary predictable base choices do not acquire the \\(4^{-k}\\) guarantee merely because there are \\(k\\) of them."
    },
    {
      "heading": "Deterministic versions",
      "text": "Although the general-purpose test is randomized, Miller–Rabin can be made deterministic in several settings.\n\nBounded input ranges\n\nFor a specified finite range of integers, proven sets of bases suffice to distinguish every prime from every composite in that range. For example, testing the twelve prime bases\n\n\\[2,3,5,7,11,13,17,19,23,29,31,37\\]\n\nis sufficient for inputs \\(n<2^{64}\\), with the usual handling of small inputs.\n\nAn implementation using a fixed base list must treat bases outside the ordinary sampling interval correctly, for example by reducing them modulo \\(n\\) and handling trivial residues. The bounded-range theorem must also match the actual input range. A base set sufficient for 64-bit integers is not thereby sufficient for arbitrary-precision integers.\n\nConditional deterministic testing\n\nMiller’s original approach gives a deterministic polynomial-time test under an appropriate form of the generalized Riemann hypothesis. Under that assumption, every odd composite has a witness among bases bounded by a constant multiple of \\((\\log n)^2\\), so checking all bases up to that bound suffices.\n\nWithout the hypothesis, the same small-base bound is not known to hold generally. Unconditional deterministic polynomial-time primality algorithms exist, but they use different methods."
    },
    {
      "heading": "Computational cost",
      "text": "Let \\(L\\) be the bit length of \\(n\\). Binary modular exponentiation requires \\(O(L)\\) modular multiplications, and the subsequent squaring chain also takes at most \\(O(L)\\) modular multiplications.\n\nWith schoolbook integer arithmetic, a round therefore requires\n\n\\[O(L^3)\\]\n\nbit operations, and \\(k\\) rounds require\n\n\\[O(kL^3).\\]\n\nThese expressions use asymptotic notation. Faster multiplication and modular-reduction methods improve the bit complexity. More generally, if modular multiplication of \\(L\\)-bit values costs \\(O(M(L))\\), the cost is approximately \\(O(kL\\,M(L))\\).\n\nMany composite candidates are rejected during the first round, so they do not incur the cost of all \\(k\\) rounds. Prime inputs pass every round and therefore require the full prescribed computation."
    },
    {
      "heading": "History and practical role",
      "text": "Gary L. Miller published the deterministic, hypothesis-dependent foundation in 1976. Michael O. Rabin published the randomized formulation in 1980, using the fact that a large fraction of bases reveal every odd composite.\n\nMiller–Rabin became a standard tool for generating large probable primes. A typical process produces candidates of a desired bit length, eliminates those divisible by small primes, and applies several Miller–Rabin rounds to the survivors. The prime number theorem explains why primes remain sufficiently frequent among large integers for repeated candidate generation to be practical.\n\nThe test has several important limitations:\n\n- Probable primality is not a primality proof. Passing random rounds provides a quantified error bound, not a general proof of primality.\n- The arithmetic must be exact. Overflow in fixed-width multiplication can invalidate modular computations, even when the mathematical algorithm is correct.\n- The base-selection procedure is part of the guarantee. Biased or dependent selections require separate analysis.\n- Witness detection is not general factorization. A rejected candidate is known to be composite, but its factors may remain unknown.\n- Fixed bases have bounded guarantees. A proven finite base set must not be extended beyond its established range without justification.\n\nWhere a verifiable primality certificate is required, Miller–Rabin can serve as a preliminary filter before a separate primality-proving procedure."
    }
  ],
  "links": [
    "primality-test",
    "algorithm",
    "integer",
    "prime-number",
    "number-theory",
    "modular-arithmetic",
    "fermats-little-theorem",
    "finite-field",
    "modular-exponentiation",
    "greatest-common-divisor",
    "monte-carlo-method",
    "conditional-probability",
    "generalized-riemann-hypothesis",
    "big-o-notation",
    "prime-number-theorem",
    "mathematical-proof"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}