What is the fastest way (general method) to calculate the quantity $a^b \!\mod c$? For example $a=2205$, $b=23$, $c=4891$.
|
Let's assume that For a specific exponent For the specific exponent Another approach that can produce faster results when If the base Also it might be advantageous if |
|||
|
|
|
The square-and-multiply algorithm is generally the fastest way to do modular exponentiation. |
|||
|
|
|
The Russian peasant's method is pretty straightforward for computing $a^b\bmod m$:
|
|||
|
|
|
One common way of fast exponentiation, either in modular arithmetic or in general, is exponentiation by squaring. Here is the section where they talk specifically about $a^b\bmod c$. |
||||
|
|
|
Generally repeated squaring works well. It deserves to be better known that this arises simply from writing the exponent in binary radix in Horner polynomial form, i.e. $\rm\ d_0 + x\ (d_1 + x\ (d_2\ +\:\cdots))\:.\ $ Below is an example of computing $\rm\ a^{101}\ $ by repeated squaring. Note that the repeated square form arises simply from performing various substitutions into the binary polynomial Horner form namely $\rm\ 1\to a,\ \ 0\to 1,\ \ (x)\:2\to (x)^2\ $ into $101_{10} = 1100101_2\ $ expanded into Horner form, viz.
|
||||
|
|
