spider68

find (x^y)%z

Apr 3rd, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. // Iterative C++ program to compute modular power
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. /* Iterative Function to calculate (x^y)%p in O(log y) */
  6. int power(int x, unsigned int y, int p)
  7. {
  8.     int res = 1;     // Initialize result
  9.  
  10.     x = x % p; // Update x if it is more than or
  11.                 // equal to p
  12.  
  13.     if (x == 0) return 0; // In case x is divisible by p;
  14.  
  15.     while (y > 0)
  16.     {
  17.         // If y is odd, multiply x with result
  18.         if (y & 1)
  19.             res = (res*x) % p;
  20.  
  21.         // y must be even now
  22.         y = y>>1; // y = y/2
  23.         x = (x*x) % p;
  24.     }
  25.     return res;
  26. }
  27.  
  28. // Driver code
  29. int main()
  30. {
  31.     int x = 2;
  32.     int y = 5;
  33.     int p = 13;
  34.     cout << "Power is " << power(x, y, p);
  35.     return 0;
  36. }
  37.  
  38. // This code is contributed by shubhamsingh10
Add Comment
Please, Sign In to add comment