Modular Exponentiation Algorithm in C++

This C++ Program demonstrates the implementation of Modular Exponentiation Algorithm.

Here is source code of the C++ Program to demonstrate the implementation of Modular Exponentiation Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* 
  2.  * C++ Program to Implement Modular Exponentiation Algorithm
  3.  */
  4. #include <iostream>
  5. #define ll long long
  6. using namespace std; 
  7.  
  8. /* 
  9.  * Function to calculate modulus of x raised to the power y 
  10.  */
  11. ll modular_pow(ll base, ll exponent, int modulus)
  12. {
  13.     ll result = 1;
  14.     while (exponent > 0)
  15.     {
  16.         if (exponent % 2 == 1)
  17.             result = (result * base) % modulus;
  18.         exponent = exponent >> 1;
  19.         base = (base * base) % modulus;
  20.     }
  21.     return result;
  22. }
  23. /* 
  24.  * Main
  25.  */
  26. int main()
  27. {
  28.     ll x, y;
  29.     int mod;
  30.     cout<<"Enter Base Value: ";
  31.     cin>>x;
  32.     cout<<"Enter Exponent: ";
  33.     cin>>y;
  34.     cout<<"Enter Modular Value: ";
  35.     cin>>mod;
  36.     cout<<modular_pow(x, y , mod);
  37.     return 0;
  38. }

$ g++ mod_exponentiation.cpp
$ a.out
 
Enter Base Value: 2
Enter Exponent: 5
Enter Modular Value: 23
9
 
------------------
(program exited with code: 1)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.