Within a computers architecture as numbers are stored in binary calculating mod is simple as taking the least significant bits. Therefore it is quite cheap. However, when the value is not it can get harder.
This is the problem we want to solve in the next step. We would like an algorithm that is linear in which would be the input size. Note that , and are all bounded by so if this appears in our bound we will be exponential.
It is quite easy to calculate (mod ) as you recursively calculate (mod ). Using this idea we get a first attempt at solving the above problem.
resursive_mod_exp(x,y,N): Input: n-bit integers x,y,N >= 0 Ouput: x^y mod N1. if y = 0, return 12. z = resursive_mod_exp(x, floor(y/2), N)3. if y is even return z^2 mod N4. if y is off return xz^2 mod N
Run time
The algorithm runs for at most loops as is an -bit integer. Calculating multiplication of -bit integers takes . Therefore this algorithm runs in time.
You can't use 'macro parameter character #' in math mode\overline{N} = \overline{N} \cdot 1 = \overline{N} \cdot x \cdot x^{-1} = 0 \cdot x^{-1} = 0 \ (mod \ N).$$ Therefore $\overline{N} = N$ and $gcd(x, N) = 1$. ## $\Leftarrow$ Consider the set of numbers $S = \{ i \cdot x \ mod \ N \vert 0 \leq i < N\}$. We know $\vert S \vert = N$ and for $s \in S$ we have $0 \leq s < N$. Suppose $$ i \cdot x = j \cdot x \ (mod \ N).$$ for $0 \leq i \leq j < N$. This gives us $$ (j - i) \cdot x = 0 \ (mod \ N).$$ Set $j-i := k$ where $0 \leq k < N$ now we have $k \cdot x = c \cdot N$. However as $gcd(x, N) = 1$ we have $N \vert k \cdot x$ giving $N \vert k$ making $k = 0$. Therefore all of $S$ are unique, so $1 \in S$ and we have a multiplicative inverse.Link to original
Though knowing an inverse exists isn’t helpful algorithmically.
Euclid(x,y): Input: integers x,y where x >= y >= 0 Output: gcd(x,y)1. If y = 0 return x2. return Eculid(y, x mod y)
Run time
If and are -bit integers then calculating mod takes time. From Claim 1 we have every 2 rounds decreases by at least a factor of 2. So there are at most rounds giving this algorithm a run time of .
extended_euclidean(x,y): Input: integers x, y where x >= y >= 0 Output: integers d, a, b where d = gcd(x,y) and d = xa + yb1. if y = 0, return (x,1,0)2. (d, a', b') = extended_euclidean(y,x mod y)3. return (d, b', a' - floor(x/y)b')
Runtime
Notice this is functionally the same as Euclidean algorithm. So if are -bit integers then this takes .
Correctness
The fact that is correct follows from Euclid’s rule.
We proceed by induction on .
If then and we are done.
Suppose we have it true for all and we want to check it is correct for .
We run extended_euclidean(y,x mod y) lets set mod as we get back correct such that and .
Now write
where . Then calculate
Misplaced && = b' c y + b' z + a' y - c b' y\\ & = b' z + a' y\\ & = d \end{align*}$$ giving what is required. Thus we get the result by induction.Link to original