Advertisement
Jasir

Extended Euclid

Aug 14th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.45 KB | None | 0 0
  1. int gcdExtended(int a, int b, int *x, int *y){
  2.     if (a == 0){
  3.         *x = 0, *y = 1;
  4.         return b;
  5.     }
  6.     int x1, y1;
  7.     int gcd = gcdExtended(b%a, a, &x1, &y1);
  8.     *x = y1 - (b/a) * x1;
  9.     *y = x1;
  10.     return gcd;
  11. }
  12.  
  13. int modInverse(int a, int m){
  14.     //(a*x)%m = 1
  15.     int x, y;
  16.     int g = gcdExtended(a, m, &x, &y);
  17.     if (g != 1)
  18.         return -1;
  19.     else{
  20.         int res = (x%m + m) % m;
  21.         return res;
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement