tinycodinglm / math /math-0160.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame
1.5 kB
opencode trace
System You are an expert mathematician and programmer.

You are an expert mathematician and programmer.

User

Show extended Euclidean algorithm implementations

Assistant

Recursive C++:
tuple<long long, long long, long long> extgcd(long long a, long long b) {
if (b == 0) return {a, 1, 0};
auto [g, x, y] = extgcd(b, a % b);
return {g, y, x - (a/b)*y};
}

Iterative C++ (preferred, no stack overflow):
long long extgcd(long long a, long long b, long long &x, long long &y) {
long long old_r = a, r = b;
long long old_s = 1, s = 0;
long long old_t = 0, t = 1;
while (r != 0) {
long long q = old_r / r;
tie(old_r, r) = make_pair(r, old_r - q * r);
tie(old_s, s) = make_pair(s, old_s - q * s);
tie(old_t, t) = make_pair(t, old_t - q * t);
}
x = old_s; y = old_t;
return old_r; // gcd
}

Modular inverse:
long long modinv(long long a, long long m) {
long long x, y;
long long g = extgcd(a, m, x, y);
if (g != 1) return -1; // no inverse
return (x % m + m) % m;
}

Linear Diophantine:
bool diophantine(long long a, long long b, long long c, long long &x, long long &y) {
long long g = extgcd(a, b, x, y);
if (c % g != 0) return false;
x *= c/g; y *= c/g;
return true;
}