Knowledge Dump

modular_exp (C++17)

Even though end results of terms like $123456789^{987654321} \mod 4321$ are relatively small, calculating them with regular power functions will likely fail, since the modulo operator isn't taken into account. A way to avoid this, is using "exponentiation by squaring": Assuming three integers bigger 1 $x,p,m$, the following statement holds true: $$x^p\mod m= \begin{cases} \left(x^{p/2}\mod m\right)^2\mod m, & \text{for }p\text{ even,}\\ \left(x\cdot \left(x^{p-1}\mod m\right)\right)\mod m, & \text{for }p\text{ odd.} \end{cases} $$ Repeated application of this rule allows safe exponentiation with large exponents.
The following function applies this method recursively for integers of type long long. Since long long is a 64bit integer, any base or modulo value bigger than $\sqrt{2^{63}-1}\approx 3\cdot 10^9$ still poses a risk for an integer overflow. To avoid this issue altogether, numeric data types of unlimited size could be used.
Download(zip).