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
- 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
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- 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
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.