![]() |
VOOZH | about |
Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7
Examples:
Input : base = 2, exp = 2
Output : 4
Input : base = 5, exp = 100000
Output : 754573817
In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the values of is being calculated it can get very large so instead we have to calculate (%modulus value.) We can use the modulus in our naive way by using modulus on all the intermediate steps and take modulus at the end, but in competitions it will definitely show TLE. So, what we can do. The answer is we can try exponentiation by squaring which is a fast method for calculating exponentiation of a number. Here we will be discussing two most common/important methods:
Binary Exponentiation
As described in this article we will be using following formula to recursively calculate (%modulus value):
Output :
754573817
Time Complexity: O(log exp) since the binary exponentiation algorithm divides the exponent by 2 at each recursive call, resulting in a logarithmic number of recursive calls.
Space Complexity: O(log exp)
-ary method:
In this algorithm we will be expanding the exponent in base (k>=1), which is somehow similar to above method except we are not using recursion this method uses comparatively less memory and time.
Output :
754573817
Time Complexity: O(log exp)
Space Complexity: O(1)
The basic idea behind the algorithm is to use the binary representation of the exponent to compute the power in a faster way.
Specifically, if we can represent the exponent as a sum of powers of 2, then we can use the fact that x^(a+b) = x^a * x^b to compute the power.
Approach :
The steps of the algorithm are as follows :
1. Initialize a result variable to 1, and a base variable to the given base value.
2. Convert the exponent to binary format.
3. Iterate over the bits of the binary representation of the exponent, from right to left.
4. For each bit, square the current value of the base.
5. If the current bit is 1, multiply the result variable by the current value of the base.
6. Divide the exponent by 2, discarding the remainder.
7. Continue the iteration until all bits of the exponent have been processed.
8. Return the result variable modulo the given modulus value.
754573817
Time Complexity -- O( log(exp) )
Space Complexity -- O(1)
Applications: Besides fast calculation of this method have several other advantages, like it is used in cryptography, in calculating Matrix Exponentiation et cetera.