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 Last Digit of a^b for Large Numbers
- Find the value of XXXX.....(N times) % M where N is large
- 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
- GCD of two numbers when one of them can be very large
- Sum of two large numbers
- LCM of two large numbers
- Difference of two large numbers
- Remainder with 7 for large numbers
- Comparing X^Y and Y^X for very large values of X and Y
- Divisible by 37 for large numbers
- Divisibility by 12 for a large number
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.