Advertisement
marius7122

Untitled

Jun 5th, 2021
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.59 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. ifstream fin("inversmodular.in");
  7. ofstream fout("inversmodular.out");
  8.  
  9. int gcdExtended(int a, int n, int &x, int &y)
  10. {
  11.     if(a == 0)
  12.     {
  13.         x = 0;
  14.         y = 1;
  15.         return n;
  16.     }
  17.     int x1, y1;
  18.     int gcd = gcdExtended(n % a, a, x1, y1);
  19.     x = y1 - x1 * (n / a);
  20.     y = x1;
  21.     return gcd;
  22. }
  23.  
  24. int modInv(int a, int n)
  25. {
  26.     int x, y;
  27.     int gcd = gcdExtended(a, n, x, y);
  28.  
  29.     if(gcd != 1)
  30.         return -1;
  31.     else
  32.         return (1ll * x + n) % n;
  33. }
  34.  
  35. int main()
  36. {
  37.     int  a, n;
  38.     fin >> a >> n;
  39.  
  40.     fout << modInv(a, n) << '\n';
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement