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.

**Examples:**

Input:a = 2, b = 3, m = 17

Output:8

2 ^ 3 % 17 = 8

Input:a = 3, b = 100000000000000000000000000, m = 1000000007

Output:835987331

**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.

Hence,

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:

## C++

// C++ program to find // (a^b)%m for b very large. #include <bits/stdc++.h> #define ll long long int using namespace std; // Function to find power ll power(ll x, ll y, ll p) { ll res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with the result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Driver Code int main() { ll a = 3; // String input as b is very large string b = "100000000000000000000000000"; ll remainderB = 0; ll MOD = 1000000007; // Reduce the number B to a small number // using Fermat Little for (int i = 0; i < b.length(); i++) remainderB = (remainderB * 10 + b[i] - '0') % (MOD - 1); cout << power(a, remainderB, MOD) << endl; return 0; }

## Java

// Java program to find // (a^b)%m for b very large. import java.io.*; class GFG { // Function to find power static long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with the result if ((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Driver Code public static void main (String[] args) { long a = 3; // String input as // b is very large String b = "100000000000000000000000000"; long remainderB = 0; long MOD = 1000000007; // Reduce the number B to a small // number using Fermat Little for (int i = 0; i < b.length(); i++) remainderB = (remainderB * 10 + b.charAt(i) - '0') % (MOD - 1); System.out.println(power(a, remainderB, MOD)); } } // This code is contributed by anuj_67.

**Output:**

835987331

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.