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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find (a^b)%m where 'b' is very large
- GCD of two numbers when one of them can be very large
- Recursive sum of digit in n^x, where n and x are very large
- Check whether a very large number of the given form is a multiple of 3.
- Series summation if T(n) is given and n is very large
- Comparing X^Y and Y^X for very large values of X and Y
- Number of factors of very large number N modulo M where M is any prime number
- Print all K digit repeating numbers in a very large number
- How to store a very large number of more than 100 digits in C++
- Multiply large integers under large modulo
- 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
- 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 smallest possible Number from a given large Number with same count of digits
- Find all Factors of Large Perfect Square Natural Number in O(sqrt(sqrt(N))
- Factorial of a large number
- Remainder with 7 for large numbers
- Sum of two large numbers