Created
April 23, 2015 08:20
-
-
Save komasaru/03c42ccb8ea0eda3722e to your computer and use it in GitHub Desktop.
C++ source code to compute modular exponetiation recursively.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*************************************************************** | |
* 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