中国剩余定理

Chinese Remainder Theorem (CRT).

今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?

— 孙子算经

The Chinese remainder theorem (CRT) is a theorem which gives a unique solution to a simultaneous linear congruences with coprime moduli. In its basic form, the CRT will determine a number pp that, when divided by some given divisors, leaves given remainders.

If m1,...,mkm_1,...,m_k are pairwise coprime, i.e., gcd⁡(mi,mj)=1\gcd(m_i,m_j)=1 for i≠ji\neq j, then the following system

{ x≡a1(modm1) x≡a2(modm2) ..., x≡ak(modmk) \begin{cases} \ x\equiv a_1 \pmod{m_1} \\ \ x\equiv a_2 \pmod{m_2} \\ \ ..., \\ \ x\equiv a_k \pmod{m_k} \end{cases}

has exactly one solution in the sense of module M=Πi=1kmiM=\Pi_{i=1}^k m_i for any a1,a2,...,ak∈Za_1,a_2,...,a_k\in \mathbb{Z}.

We define Mi=M/miM_i=M/m_i and ti≡Mi−1(modmi)t_i\equiv M_i^{-1}\pmod{m_i}, then the solution to this congruences is x≡∑i=1kaiMiti(modM)x\equiv \sum_{i=1}^k a_iM_it_i \pmod{M}. Note that xx is unique modulo MM.

The proof of correctness and uniqueness of CRT: My CnBlogs or OI Wiki-CRT

Code Implementation

cpp
long long CRT(int k, long long* a, long long* m) {
    long long M = 1, ans = 0;
    for (int i = 1; i <= k; ++i)
        M = M * m[i];
	for (int i = 1; i <= k; ++i) {
        long long Mi = M / m[i], ti, _;
        exgcd(Mi, m[i], ti, _); // get inverse: ti * Mi mod m[i] = 1
        ans = (ans + a[i] * Mi % M * ti % M) % M;
    }
    return (ans % M + M) % M;
}
Eureka moment!

数论的定理多如牛毛,在众多熟悉或不熟悉的外国名字中看到一个「中国」剩余定理还是非常之亲切的。

CRT 提供了互质模数的线性同余方程组的解。在密码学中 CRT 经常被运用于简化模意义下求幂的运算。具体来说,对于合数模数 MM 且 gcd⁡(M,a)≠1\gcd(M,a)\neq 1 的情况,可以应用 CRT 简化 aemod  Ma^e\mod{M} 的计算。此外,CRT 还能用于加速 RSA 的解密过程 (RSA decryption)。

m=cdmod  N⇒{m≡cdmod  pm≡cdmod  q⇒{m≡(cmod  p)dmod  (p−1)mod  pm≡(cmod  q)dmod  (q−1)mod  q m=c^d\mod{N} \Rightarrow \begin{cases} m\equiv c^d\mod{p} \\m\equiv c^d \mod{q} \end{cases} \Rightarrow \begin{cases} m\equiv (c\mod p)^{d\mod{(p-1)}}\mod{p}\\ m\equiv (c\mod q)^{d\mod{(q - 1)}}\mod{q} \end{cases}

Bob (Receiver) 是知道 NN 的两个 factor pp 与 qq 的,因此其先将朴素的解密过程转化为这一线性同余方程组,并应用 CRT 得到方程的解,也即消息 mm。这一解密方式比直接计算 cdmod  Nc^d\mod{N} 快了 44 倍左右。

P.S. RSA 问题是一个著名的困难问题 (hard problems),我将会在 P3 中进行介绍。