I want to reduce a multi-precision integer $x$ modulo a prime $p$, very fast. Performing the traditional Euclidean division for only calculating the modulo, is inefficient and modular reduction is at the heart of many Cryptographic primitives like Elliptic Curve Cryptography. There are other methods to perform the aforementioned task like Barret reduction, etc, but I would like to learn about Montgomery reduction and its peculiarities first, because of its practical significance. Algorithm:
Input : Integer x, n, k
Output : (2^(-k) * x) mod n
1. for t from 1 to k do
1.1 if x is odd then
1.1.1 x <- x+n
1.2 x <- x/2
2 Return x
There are restrictions on $x$ like, $0$ <= $x$ < $n^2$, and also, $n$ should be odd. The book from which, I borrowed the above algorithm from , states two facts:
Fact 1 : Adding n to x does not change the residue, since in effect it adds one to the quotient ⌊x/n⌋. Another way to explain this is that n is (or multiples of n are) congruent to zero modulo n. Adding zero will not change the value of the residue.
Fact 2: If $x$ is even, then performing a division by two in $Z$ is congruent to $x · 2^{−1} \mod n$ . Actually, this is an application of the fact that if x is evenly divisible by any $k$ ∈ $Z$, then division in Z will be congruent to multiplication by $k^{−1}$ modulo $n$ .
I don't understand the meaning behind Fact 2. In reality, I'm having trouble in comprehending how the author transcends from regular arithmetic to modular arithmetic mod n ? Why is it that division of $x$ by two in $Z$ (integers) is congruent to multiplication by $2^{-1}$ in modulo $n$. After all $2^{-1}\mod n$ can be easily calculated by the extended euclidean algorithm: Since, $n = 2*q + r$. Since $n$ is odd, $r$ should be $1$. Therefore on transposing, we get: $n - 2*q = 1$. If we take this preceding equation modulo $n$, we get $-q$ as the multiplicative inverse of $2$ w.r.t mod n.
It would be highly appreciated, if I could get a good explanation of how Montgomery reduction works, in the first place. Why do we keep adding $n$ to $x$ , if $x$ is odd?
I am missing some very great clarity in my understanding! What are the solid principles behind Montgomery multiplication with reduction ? Since, I come from mostly programming background, I seem to be lacking some mathematical knowledge in this context.
Every help will be greatly appreciated!