![]() |
VOOZH | about |
Given three numbers a, b and m where 1<=b,m<=10^6 and 'a' may be very large and contains upto 10^6 digits. The task is to find (a^b)%m.
Examples:
Input : a = 3, b = 2, m = 4 Output : 1 Explanation : (3^2)%4 = 9%4 = 1 Input : a = 987584345091051645734583954832576, b = 3, m = 11 Output: 10
This problem is basically based on modular arithmetic. We can write (a^b) % m as (a%m) * (a%m) * (a%m) * ... (a%m), b times. Below is a algorithm to solve this problem :
10
Time Complexity: O(len(a)+b)
Auxiliary Space: O(1)
Efficient Approach: The above multiplications can be reduced to log b by using fast modular exponentiation where we calculate result by the binary representation of exponent (b). If the set bit is 1 we multiply current value of base to result and square the value of base for each recursive call.
Recursive Code:
10
Time Complexity: O(len(a)+ log b)
Auxiliary Space: O(log b)
Space Efficient Iterative Code:
10
Time Complexity: O(len(a)+ log b)
Auxiliary Space: O(1)
Case: When both 'a' and 'b' are very large.
We can also implement the same approach if both 'a' and 'b' was very large. In that case, we would have first took mod of it with m using our aModM function. Then pass it to the above ApowBmodM recursive or iterative function to get the required result.
Recursive Code:
546081867
Time Complexity: O(len(a)+len(b)+log b)
Auxiliary Space: O(log b)
Space Efficient Iterative Code:
546081867
Time Complexity: O(len(a)+len(b)+ log b)
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.