Performing Exponentiation
Last updated
Last updated
Method is based on the fact that can quickly calculate powers of a number that are themselves powers of 2.
For two numbers base and exp, to compute under Modulo
The basis for the fast exponentiation algorithm is to build bigger and bigger powers of A and use the binary digits of the exponent to decide which of those should be multiplied into the final result.
The steps of the algorithm are as follows
Initialize a result variable to 1, and a base variable to the given base value.
Iterate over the bits of the binary representation of the exponent, from right to left.
For each bit, square the current value of the base.
If the current bit is 1, multiply the result variable by the current value of the base.
Continue the iteration until all bits of the exponent have been processed.
3. Return the result variable modulo the given modulus value.
One limitation of this algorithm is that values raised to large powers grow extremely large.
Reducing each number with the modulus makes each step slightly slower, but can calculate values of practically unlimited size.
Time Complexity =
Space Complexity =