Advertisement
JosepRivaille

P29212: Exponenciació modular

Mar 7th, 2016
500
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.45 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. //Right-to-left binary method
  6. int calculate(int &b, int& e, int& m)
  7. {
  8.     if (m == 0) return 0;
  9.     int result = 1;
  10.     b = b % m;
  11.     while (e > 0) {
  12.       if (e%2 == 1) result = (result * b) % m;
  13.       e = e >> 1;
  14.       b = (b * b) % m;
  15.     }
  16.     return result;
  17. }
  18.  
  19.  
  20. int main()
  21. {
  22.   int b, e, m;
  23.   while (cin >> b >> e >> m) {
  24.     cout << calculate(b, e, m) << endl;
  25.   }
  26. }
  27.  
  28. /JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement