1

Let $p$ and $q$ be relative primes, $n$ positive integer.

Given

  • $n\bmod p$ and
  • $n\bmod q$

how do I calculate $n\bmod (pq)$ ?

Brian M. Scott
  • 616,228
Dave
  • 920

3 Answers3

5

Since $p$ and $q$ are relatively prime, there are integers $a$ and $b$ such that $ap+bq=1$. You can find $a$ and $b$ using the Extended Euclidean algorithm. Then $n\equiv aps+bqr \bmod pq$ if $n\equiv r \bmod p$ and $n\equiv s \bmod p$.

As pedja mentioned, this is a constructive proof of the Chinese remainder theorem.

lhf
  • 216,483
3

From the fact that $p,q$ are relatively prime, we can find coefficients $a,b$ such that:

$$ap + bq = 1$$

With these coefficients we can piece together a solution for n from its residues modulo $p$ and $q$. Say:

$$n \equiv r \mod p$$ $$n \equiv s \mod q$$

Then this works: $ n = sap + rbq $ since:

$$bq \equiv 1 \mod p$$ $$ap \equiv 1 \mod q$$

Of course the above expression for $n$ can be reduced modulo $pq$ without affecting the residues modulo $p$ and $q$.

hardmath
  • 37,015
3

One may use the Bezout identity $\rm\:a\:p + b\:q = 1\:$ obtained by the extended Euclidean algorithm. But, in practice, it's often more convenient to use the form below, e.g. see my Easy CRT posts.

Theorem (Easy CRT) $\rm\ \ $ If $\rm\ p,\:q\:$ are coprime integers then $\rm\ p^{-1}\ $ exists $\rm\ (mod\ q)\ \ $ and

$\rm\displaystyle\quad\quad\quad\quad\quad \begin{eqnarray}\rm n&\equiv&\rm\ a\ (mod\ p) \\ \rm n&\equiv&\rm\ b\ (mod\ q)\end{eqnarray} \ \iff\ \ n\ \equiv\ a + p\ \bigg[\frac{b-a}{p}\ mod\ q\:\bigg]\ \ (mod\ p\:\!q)$

Proof $\rm\ (\Leftarrow)\ \ \ mod\ p\!:\:\ n\equiv a + p\ (\cdots)\equiv a\:,\ $ and $\rm\ mod\ q\!:\:\ n\equiv a + (b-a)\ p/p \equiv b\:.$

$\rm\ (\Rightarrow)\ \ $ The solution is unique $\rm\ (mod\ p\!\:q)\ $ since if $\rm\ x',\:x\ $ are solutions then $\rm\ x'\equiv x\ $ mod $\rm\:p,q\:$ therefore $\rm\ p,\:q\ |\ x'-x\ \Rightarrow\ p\!\:q\ |\ x'-x\ \ $ since $\rm\ \:p,\:q\:$ coprime $\rm\:\Rightarrow\ lcm(p,q) = p\!\:q\:.\quad$ QED

Bill Dubuque
  • 272,048