Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created April 23, 2015 08:19
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/573f949235ef5d57ea2f to your computer and use it in GitHub Desktop.
Save komasaru/573f949235ef5d57ea2f to your computer and use it in GitHub Desktop.
C++ source code to compute modular exponetiation iteratively.
/***************************************************************
* Modular Exponentiation (iterative).
**************************************************************/
#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)
{
ans = 1;
while (e > 0) {
if ((e & 1) == 1) ans = (ans * b) % m;
e >>= 1;
b = (b * b) % m;
}
return ans;
}
int main()
{
try
{
// Declaration
int b, e, m, me; // me = b^e mod m
b = 12345; e = 6789; m = 4567;
// Instantiation
ModularExponentiation objMain;
// Modular Exponentiation Computation
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