4

If we are given a number $n$, and two primes $p_1$ and $p_2$, and we have $a = n$ modulo $p_1$ and $b = n$ modulo $p_2$, can $n$ modulo $p_1p_2$ be evaluated using $a$ and $b$?

Zev Chonoles
  • 132,937
Mod
  • 693
  • 4
    Yes, this is the Chinese Remainder Theorem. – André Nicolas Aug 24 '13 at 16:38
  • Well , the edit has changed the question meaning, i had meant that a = n%p1 and b = n%p2 . – Mod Aug 24 '13 at 16:40
  • @Mod: Well, I've reverted the phrasing there to what you had before, which is hopefully acceptable. I assumed you wanted the $\equiv$ sign (\equiv) but didn't know how to make it. Also, this doesn't really change anything; André Nicolas' comment is still correct. – Zev Chonoles Aug 24 '13 at 16:42
  • Well, before posting the question I had read the chinese remainder theorem and could not see how it could be applied over here , if somebody could explain it , it would be of much help. – Mod Aug 24 '13 at 16:46

2 Answers2

8

You are asking about a special case of the Chinese Remainder Theorem. (Please see the Wikipedia article, or any beginning book in Number Theory.)

Let us call the primes $p$ and $q$, and assume they are distinct. First find numbers $s$ and $t$ such that $qs \equiv 1\pmod p$ and $pt\equiv 1\pmod{q}$. For large $p$ and $q$, we can do this using the Extended Euclidean Algorithm. For small $p$ and $q$, one can often do it by inspection.

Then $$n\equiv aqs+bpt\pmod {pq}.$$ We now verify that the above expression is correct. Note that $aqs+bpt\equiv aqs \pmod{p}$. But by the choice of $s$, we have $qs\equiv 1\pmod{p}$, so $aqs+bpt\equiv a \pmod{p}$. Similarly, $aqs+bpt\equiv b \pmod{q}$.

Note that once we have precomputed $s$ and $t$, they can be used for any given values of $a$ and $b$.

André Nicolas
  • 514,336
0

The short answer is that if $x \equiv x_0\ (\text{mod}\ p_0)$ and $x \equiv x_1\ (\text{mod}\ p_1)$ then

$$x\equiv p_0*(p_0^{-1}\ \text{mod}\ p_1)*(x_1-x_0) \hspace{1em} (\text{mod}\ p_0p_1)$$

As André has already noted, this is a consequence of the Chinese Remainder Theorem, and more directly Garner's algorithm. Garner's algorithm works by assuming $x$ has the form $v_0+p_0v_1+p_0p_1v_2+\dots$ and using the residues to solve for the various $v_i$.

Concretely, if you have residues $xs=[x_0,x_1,\dots]$ and prime powers $m=p_0^{k_0} p_1^{k_1}\dots$ you may calculate $x\ \text{mod}\ m$ by the following simple procedure:

def garner(xs, ps, m):
    r, q = 0, 1
    for x, p^k in zip(xs, ps):
        r += q * inv(q, p^k) * (x - r)
        r %= m
        q *= p^k
    return r

Where $\text{inv}(n, p^k)$ returns the inverse of $n$ modulo $p^k$. (This can easily be calculated using fast exponentiation and Euler's formula as $n^{p^{k-1}(p-1)-1}\ \text{mod}\ p^k$).

Thomas Ahle
  • 5,629