File size: 1,500 Bytes
d517dc9
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "math-0160", "name": "Extended Euclidean Algorithm Implementations"}
{"type": "message", "message": {"role": "system", "content": "You are an expert mathematician and programmer."}}
{"type": "message", "message": {"role": "user", "content": "Show extended Euclidean algorithm implementations"}}
{"type": "message", "message": {"role": "assistant", "content": "Recursive C++:\ntuple<long long, long long, long long> extgcd(long long a, long long b) {\n  if (b == 0) return {a, 1, 0};\n  auto [g, x, y] = extgcd(b, a % b);\n  return {g, y, x - (a/b)*y};\n}\n\nIterative C++ (preferred, no stack overflow):\nlong long extgcd(long long a, long long b, long long &x, long long &y) {\n  long long old_r = a, r = b;\n  long long old_s = 1, s = 0;\n  long long old_t = 0, t = 1;\n  while (r != 0) {\n    long long q = old_r / r;\n    tie(old_r, r) = make_pair(r, old_r - q * r);\n    tie(old_s, s) = make_pair(s, old_s - q * s);\n    tie(old_t, t) = make_pair(t, old_t - q * t);\n  }\n  x = old_s; y = old_t;\n  return old_r;  // gcd\n}\n\nModular inverse:\nlong long modinv(long long a, long long m) {\n  long long x, y;\n  long long g = extgcd(a, m, x, y);\n  if (g != 1) return -1;  // no inverse\n  return (x % m + m) % m;\n}\n\nLinear Diophantine:\nbool diophantine(long long a, long long b, long long c, long long &x, long long &y) {\n  long long g = extgcd(a, b, x, y);\n  if (c % g != 0) return false;\n  x *= c/g; y *= c/g;\n  return true;\n}"}}