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:
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.
- Fermat’s little theorem
- Modulo power for large numbers represented as strings
- Sum of elements of all partitions of number such that no element is less than K
- Find Last Digit of a^b for Large Numbers
- Multiply Large Numbers represented as Strings
- Number of ways to change the XOR of two numbers by swapping the bits
- Number of quadrilaterals possible from the given points
- How to read Competitive Programming Questions?
- Python in Competitive Programming
- Maximize the total profit of all the persons