Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created April 23, 2015 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/03c42ccb8ea0eda3722e to your computer and use it in GitHub Desktop.
Save komasaru/03c42ccb8ea0eda3722e to your computer and use it in GitHub Desktop.
C++ source code to compute modular exponetiation recursively.
/***************************************************************
* Modular Exponentiation (recursive).
**************************************************************/
#include <iostream>
#include <stdlib.h>
using namespace std;
class ModularExponentiation
{
int ans; // Answer
public:
int compME(int, int, int); // Compute Modular Exponentiation
};
/*
* Compute Modular Exponentiation
*/
int ModularExponentiation::compME(int b, int e, int m)
{
if (e == 0) return 1;
ans = compME(b, e / 2, m);
ans = (ans * ans) % m;
if (e % 2 == 1) ans = (ans * b) % m;
return ans;
}
int main()
{
try
{
int b, e, m, me; // me = b^e mod m
b = 12345; e = 6789; m = 4567;
// Instantiation
ModularExponentiation objMain;
// Compute Modular Exponentiation
me = objMain.compME(b, e, m);
// Display
cout << b << "^" << e << " mod " << m << " = "
<< me << endl;
}
catch (...) {
cout << "ERROR!" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment