kerelius

modExpo (Java)

Dec 10th, 2021 (edited)
554
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.47 KB | None | 0 0
  1. // x^y (mod p)
  2. int modExpo(int x, int y, int p)
  3.   {
  4.     int res = 1; // Initialize result
  5.  
  6.     x = x % p; // Update x if it is more than or
  7.     // equal to p
  8.  
  9.     if (x == 0)
  10.       return 0; // In case x is divisible by p;
  11.  
  12.     while (y > 0)
  13.     {
  14.  
  15.       // If y is odd, multiply x with result
  16.       if ((y & 1) != 0)
  17.         res = (res * x) % p;
  18.  
  19.       // y must be even now
  20.       y = y >> 1; // y = y/2
  21.       x = (x * x) % p;
  22.     }
  23.     return res;
  24.   }
Add Comment
Please, Sign In to add comment