---
id: 1156
lang: en
translation_of: index.md
source_sha256: 2825d4be42201c6ca6777ccfa4ca5f647b5d1b6f393238158554941d6c304e0b
title: "Miller-Rabin & Pollard-Rho Algorithm Notes"
description: "The Miller-Robin algorithm has two parts: one is the Fermat test, and the other is quadratic probing."
tags: ["OI","Math","Nasty Problems","Godlike","Number Theory","Primes","Primality Testing"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The author's spelling “Miller-Robin” in the body (and the Chinese description) is kept as written; headings and the title say Miller-Rabin."
  - "迈克尔数 rendered literally as “Michael numbers”; the link goes to the Wikipedia article on Carmichael numbers (卡迈克尔数), but the author's name for them is kept."
  - "二次探测 and 二次探查 are used interchangeably by the author; both rendered as “quadratic probing”."
  - "Chinese text inside TeX (the display formula under Quadratic Probing, and O(上天)) is left untouched, since it is not inside \\text{…}; 上天 is chipped where it appears in prose."
  - "恩 read as the interjection 嗯, “well”."
  - "亦复如是 (a classical phrase, “and likewise again”) rendered as “and so on and so forth”."
  - "被卡常卡的心态很崩 rendered as “all that constant-squeezing has left my mindset pretty wrecked”."
---

## Miller-Rabin Primality Test

First, I strongly recommend reading [this article](https://www.crazydave.top/2018/07/23/%E6%95%B0%E8%AE%BA%E7%AE%97%E6%B3%95%E5%B0%8F%E7%BB%93/). (If you get it, there's no need to come here.)

The Miller-Robin algorithm has two parts: one is the Fermat test, and the other is quadratic probing. These two things sound very <span class="slang" data-zh="玄学" data-gloss="xuánxué, “metaphysics”. Something that seems to run on luck or mysterious rules rather than logic.">black magic</span> (and they really are), so I'll explain them clearly and include the code. The number we are testing is $p$.

<!--more-->

### The Fermat Test and Michael Numbers

Fermat's little theorem tells us that if a number $a$ is prime, then $\forall x, x^{a-1} \equiv 1 \; (mod \; a$. Intuition tells us we could try running the Fermat test with the numbers in $[1,a)$ one by one to check whether it is prime. First, the complexity of that is still <span class="slang" data-zh="上天" data-gloss="shàngtiān, “go up to the sky”. Here: astronomically high, said of a time complexity.">sky-high</span>; second, there is a class of composite numbers that can pass the Fermat test, called [Michael numbers](https://zh.wikipedia.org/wiki/%E5%8D%A2%E5%8D%A1%E6%96%AF-%E5%8D%A1%E7%B1%B3%E5%88%87%E5%B0%94%E6%95%B0). So the Fermat test can be wrong.

So how do we test efficiently?

### Quadratic Probing

But we can also use a theorem like this:

$$
\begin{gathered}\forall x, x^2 \equiv 1 (\mod\; p)\\如果p为质数 \\ 则x的解集只包含x \equiv 1或x \equiv p-1 \\ 否则p是合数。\end{gathered}
$$

So we can let $p - 1 = 2^k x$. After that, we can test by adjusting the value of $k$, using quadratic probing and the Fermat test. Let's use code to go through exactly how these tests are done:

```cpp
bool isPrime(ll p)
{
    // 把 p - 1 设为我们需要的值形式
    ll x = p - 1, k = 0, j;
    while (!(x & 1))
        x >>= 1, k++;
    // 进行随机的素数测试，这是 Miller-Rabin 的核心部分
    for (int i = 0; i <= 4; i++)
    {
        // 用于减少常数的判断
        if (p == bs[i])
            return true;
        // 算出本身的基底以便后期运算
        ll r = quick_pow(bs[i], x, p);
        // 常数判断
        if (r == 1 || r == p - 1)
            continue;
        for (j = 1; j <= k; j++)
        {
            // 重点：
            // 在二次探查中，p - 1 = 2^(kx)，如果
            // 这个出现了意外解，那么 p 就是合数
            r = r * r % p;
            if (r == p - 1)
                break;
        }
        // 判断
        if (j > k)
            return false;
    }
    return true;
}
```

## Pollard-Rho Prime Factorization

This algorithm is also a very <span class="slang" data-zh="毒瘤" data-gloss="dúliú, “tumor”. A problem (or problem setter) that is painfully hard, tedious, or full of traps.">nasty</span>, randomized, <span class="slang" data-zh="玄学" data-gloss="xuánxué, “metaphysics”. Something that seems to run on luck or mysterious rules rather than logic.">black-magic</span> algorithm. The usual prime factorization algorithm is trial division, whose time complexity is $O(\sqrt{n})$. The Pollard-Rho algorithm uses randomization to solve the factorization problem with a smaller time complexity. There is a very good set of [lecture notes](https://www.crazydave.top/wp&#45;content/uploads/2019/01/Pollard-rho%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3.pdf) (by BigBallon) on Crazydave's blog; do go and have a look.

The basis of this algorithm is actually a <span class="slang" data-zh="玄学" data-gloss="xuánxué, “metaphysics”. Something that seems to run on luck or mysterious rules rather than logic.">black-magic</span> algorithm: randomly enumerating prime factors. Yep, that's right, it's just <span class="slang" data-zh="瞎××" data-gloss="xiā ××, “blindly ××”, with ×× censoring a vulgar word. Doing something at random, with no method at all.">blindly ××</span> picking random numbers for trial division, also known as the “<span class="slang" data-zh="自我良好算法" data-gloss="zìwǒ liánghǎo suànfǎ, “self-good algorithm”, from 自我感觉良好 “feeling pleased with oneself”. A joking name for this naive guess-and-check method.">feel-good algorithm</span>”. This algorithm mainly works by enumerating factors and doing trial division. Well, the complexity of this algorithm is $O(上天)$.

So how can we optimize this seemingly unoptimizable algorithm? A <span class="slang" data-zh="玄学" data-gloss="xuánxué, “metaphysics”. Something that seems to run on luck or mysterious rules rather than logic.">black-magic</span> algorithm naturally needs a <span class="slang" data-zh="玄学" data-gloss="xuánxué, “metaphysics”. Something that seems to run on luck or mysterious rules rather than logic.">black-magic</span> optimization, so here I'll introduce a <span class="slang" data-zh="玄学" data-gloss="xuánxué, “metaphysics”. Something that seems to run on luck or mysterious rules rather than logic.">black-magic</span> theorem to speed it up.

### The Birthday Paradox

Actually, this whole paradox makes only one point:

> The probability of simply picking numbers <span class="slang" data-zh="瞎××" data-gloss="xiā ××, “blindly ××”, with ×× censoring a vulgar word. Doing something at random, with no method at all.">blindly ××</span> is $\frac{1}{n}$, but if we enumerate $k=i-j$, this probability goes up a lot.

Yes, now let me describe this theory.

If we pick numbers at random, our probability of picking the number is $\frac{1}{n}$. This probability is too small, but we can enumerate two variables so that $k=i-j$, and then our chance of getting a number goes up a lot; this can be found by computer simulation (the experimental data is in the lecture notes). The conclusion is that when we do $\sqrt{n}$ enumerations, our probability increases to $\sqrt{\frac{1}{n}}$. This is a very important finding.

### Back to the Pollard-Rho Algorithm

We can let the random function be $f(x)=(x^2+c) \mod \; n$, then make two variables $x,y$. After that we can initialize the value of $x$, then use $x$ as the seed to generate $y$, then set $x$ to $y$, and so on and so forth, and in each loop iteration we take the difference and compute $gcd(|y-x|,n)$. The code is too <span class="slang" data-zh="毒瘤" data-gloss="dúliú, “tumor”. A problem (or problem setter) that is painfully hard, tedious, or full of traps.">nasty</span>, so I won't post it (all that <span class="slang" data-zh="卡常" data-gloss="kǎ cháng, “stuck on constants”. Micro-optimising a correct solution just to fit the time limit.">constant-squeezing</span> has left my mindset pretty <span class="slang" data-zh="崩" data-gloss="bēng, “collapse”. Said of one's mindset (心态): breaking down mentally, losing all composure.">wrecked</span>).
