Advertisement
Shiam7777777

Untitled

Jan 21st, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. // Iterative C program to compute modular power
  2. #include <stdio.h>
  3.  
  4. /* Iterative Function to calculate (x^y)%p in O(log y) */
  5. int power(int x, unsigned int y, int p)
  6. {
  7.     int res = 1;     // Initialize result
  8.  
  9.     x = x % p; // Update x if it is more than or
  10.                 // equal to p
  11.  
  12.     while (y > 0)
  13.     {
  14.         // If y is odd, multiply x with result
  15.         if (y & 1)
  16.             res = (res*x) % p;
  17.  
  18.         // y must be even now
  19.         y = y>>1; // y = y/2
  20.         x = (x*x) % p;
  21.     }
  22.     return res;
  23. }
  24.  
  25. // Driver program to test above functions
  26. int main()
  27. {
  28. int x = 2;
  29. int y = 5;
  30. int p = 13;
  31. printf("Power is %u", power(x, y, p));
  32. return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement