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 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
- Recursive sum of digit in n^x, where n and x are very large
- Difference of two large numbers
- Divisible by 37 for large numbers
- Remainder with 7 for large numbers
- Divisibility by 12 for a large number
- Factorial of a large number
- Check a large number is divisible by 16 or not
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.