Given three numbers a, b and m where 1<=a, m<=10^6. Given very large 'b' containing up to 10^6 digits and m is a prime number, the task is to find (a^b)%m.
Input: a = 2, b = 3, m = 17
2 ^ 3 % 17 = 8
Input: a = 3, b = 100000000000000000000000000, m = 1000000007
Approach: According to Fermat’s little theorem,
a^(p-1) mod p = 1, When p is prime.
From this, as of the problem, M is prime, express A^B mod M as follows:
A^B mod M = ( A^(M-1) * A^(M-1) *.......* A^(M-1) * A^(x) ) mod M
Where x is B mod M-1 and A ^ (M-1) continues B/(M-1) times
Now, from Fermat’s Little Theorem,
A ^ (M-1) mod M = 1.
A^B mod M = ( 1 * 1 * ....... * 1 * A^(x) ) mod M
Hence mod B with M-1 to reduce the number to a smaller one and then use power() method to compute (a^b)%m.
Below is the implementation of the above approach:
- Find (a^b)%m where 'a' 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
- LCM of two large numbers
- GCD of two numbers when one of them can be very large
- Sum of two large numbers
- Series summation if T(n) is given and n is very large
- Divisibility by 12 for a large number
- Recursive sum of digit in n^x, where n and x are very large
- Remainder with 7 for large numbers
- Difference of two large numbers
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.