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.
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 :
- 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.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find (a^b)%m where 'b' is very large
- Find N % 4 (Remainder with 4) for a large value of N
- Find the value of XXXX.....(N times) % M where N is large
- Find Last Digit of a^b for Large Numbers
- Program to find remainder when large number is divided by 11
- Program to find remainder when large number is divided by r
- Multiply large integers under large modulo
- GCD of two numbers when one of them can be very large
- LCM of two large numbers
- Sum of two large numbers
- Divisible by 37 for large numbers
- Recursive sum of digit in n^x, where n and x are very large
- Series summation if T(n) is given and n is very large
- Remainder with 7 for large numbers
- Divisibility by 12 for a large number