VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-abm-large/

⇱ Find (a^b)%m where 'a' is very large - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find (a^b)%m where 'a' is very large

Last Updated : 11 Sep, 2023

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
Recommended Practice

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 : 

  • Since 'a' is very large so read 'a' as string.
  • Now we try to reduce 'a'. We take modulo of 'a' by m once, i.e; ans = a % m , in this way now ans=a%m lies between integer range 1 to 10^6 i.e; 1 <= a%m <= 10^6.
  • Now multiply ans by b-1 times and simultaneously take mod of intermediate multiplication result with m because intermediate multiplication of ans may exceed range of integer and it will produce wrong answer.

Output
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:


Output
10

Time Complexity: O(len(a)+ log b)

Auxiliary Space: O(log b)

Space Efficient Iterative Code:


Output
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:


Output
546081867

Time Complexity: O(len(a)+len(b)+log b)

Auxiliary Space: O(log b)

Space Efficient Iterative Code:


Output
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.
 

Comment
Article Tags:
Article Tags: