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
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.