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 firstname.lastname@example.org. 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- 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 r
- Program to find remainder when large number is divided by 11
- Multiply large integers under large modulo
- Find all Factors of Large Perfect Square Natural Number in O(sqrt(sqrt(N))
- Find smallest possible Number from a given large Number with same count of digits
- Sum of two large numbers
- GCD of two numbers when one of them can be very large
- LCM of two large numbers
- Remainder with 7 for large numbers
- Comparing X^Y and Y^X for very large values of X and Y
- Factorial of a large number