bhupixb

Extended Euclid's Algorithm

Jul 11th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. #define int long long
  5.  
  6. int extended_gcd(int a, int b, int &x, int &y) {
  7. if (!b) {
  8. // Base case a * 1 + b * 0 = gcd(a, 0)
  9. // which implies x = 1 and y = 0
  10. x = 1, y = 0;
  11. return a;
  12. }
  13. int gcd = extended_gcd(b, a % b, x, y);
  14. // a * x + b * y = d (here d is gcd(a, b))
  15. // b * x + (a % b) * y = d (after the recursive call the equation becomes this)
  16. // b * x + (a - (a / b) * y) = d
  17. // a * y + b(x - (a / b) * y) = d
  18. // which implies cofficient of a is y and cofficient of b
  19. // is (x - (a/b)*y)
  20. int x1 = y, y1 = x - (a / b) * y;
  21. x = x1, y = y1;
  22. return gcd;
  23. }
  24.  
  25. inline void solve() {
  26. int x, y;
  27. int a = rand(), b = rand();
  28. // cout << a << ' ' << b << ' ';
  29. int gcd = extended_gcd(a, b, x, y);
  30. assert(gcd == a*x+b*y);
  31. }
  32.  
  33. signed main() {
  34. ios_base::sync_with_stdio(0);
  35. cin.tie(NULL);
  36. cout.tie(NULL);
  37. srand(time(NULL));
  38. int t = 100000;
  39. // cin >> t;
  40. while(t--)
  41. solve();
  42. return 0;
  43. }
Add Comment
Please, Sign In to add comment