Find (a^b)%m where ‘a’ is very large in C++


In this tutorial, we are going to solve the equation (ab)%m where a is a very large number.

The equation (ab)%m=(a%m)*(a%m)...b_times. We can solve the problem by finding the value of a%m and then multiplying it b times.

Let's see the steps to solve the problem.

  • Initialize the numbers a, b, and m.

  • Write a function to find the a%m.

    • Initialize the number with 0.

    • Iterate over the number in string format.

    • Add the last digits to the number.

    • Update the number with number modulo them.

  • Get the value of a%m.

  • Write a loop that iterates b times.

    • Multiply the a%m and modulo the result with m.

  • Print the result.

Example

Let's see the code.

 Live Demo

#include<bits/stdc++.h>
using namespace std;
unsigned int aModm(string str, unsigned int mod) {
   unsigned int number = 0;
   for (unsigned int i = 0; i < str.length(); i++) {
      number = number * 10 + (str[i] - '0');
      number %= mod;
   }
   return number;
}
unsigned int aPowerBmodM(string &a, unsigned int b, unsigned int m) {
   unsigned int a_mod_m_result = aModm(a, m);
   unsigned int final_result = 1;
   for (unsigned int i = 0; i < b; i++) {
      final_result = (final_result * a_mod_m_result) % m;
   }
   return final_result;
}
int main() {
   string a = "123456789012345678901234567890123";
   unsigned int b = 3, m = 7;
   cout << aPowerBmodM(a, b, m) << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

1

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 01-Feb-2021

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements