Compute GCD, LCM, and Bezout coefficients x, y for ax+by=gcd with a full Euclidean step trace and modular inverse — BigInt-exact up to 10¹⁸.
Paste two non-negative integers and the Extended GCD & Bezout Calculator runs the Extended Euclidean Algorithm, producing the GCD, the LCM, and the Bezout coefficients x and y that satisfy a·x + b·y = gcd(a, b). Every step of the Euclidean division chain is shown in a table so you can follow the back-substitution by hand, useful when a contest problem asks you to prove the identity, not just quote the answer.
Competitive programmers reach for this algorithm in two situations: verifying that a modular inverse exists before computing it (the inverse only exists when gcd = 1), and solving linear Diophantine equations ax + by = c, where a solution exists exactly when gcd(a, b) divides c. All arithmetic uses JavaScript BigInt, so inputs up to 10¹⁸ are exact with no floating-point rounding and no silent overflow.
Load the sample (252 and 198) and the step trace shows four division rows: 252 = 1·198 + 54, then 198 = 3·54 + 36, then 54 = 1·36 + 18, then 36 = 2·18 + 0. The remainder hits zero at 18, so GCD = 18. Back-substitution yields x = −3, y = 4, verified by 252·(−3) + 198·4 = −756 + 792 = 18. The identity check row confirms this automatically. LCM = 252 × 198 / 18 = 2,772. Because gcd = 18 is not 1, no modular inverse exists for this pair, and the tool reports "An inverse exists only when gcd(a, b) = 1" rather than a silent wrong answer.
Try a = 6, b = 9. GCD = 3, so no modular inverse exists. The tool shows the exact guard message rather than computing a meaningless result; the bundled C++ snippet returns -1 in this case, which is the convention most competitive-programming templates follow. Entering 0 for both values triggers a separate guard: gcd(0, 0) is undefined, so the algorithm has no meaningful output and the tool says so immediately. The step table is not shown for this input because there are no division steps to trace.
1827724-518Euclidean Step Trace
| Step | a | b | q = a÷b | r = a mod b |
|---|---|---|---|---|
| 1 | 252 | 198 | 1 | 54 |
| 2 | 198 | 54 | 3 | 36 |
| 3 | 54 | 36 | 1 | 18 |
| 4 | 36 | 18 | 2 | 0 ← gcd |
C++ — Extended GCD Template
// Extended GCD — returns gcd(a,b); sets x,y so that a*x + b*y = gcd
long long extgcd(long long a, long long b, long long &x, long long &y) {
if (b == 0) { x = 1; y = 0; return a; }
long long x1, y1;
long long g = extgcd(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return g;
}
// Usage
long long x, y;
long long g = extgcd(a, b, x, y);
// Now: a*x + b*y == g
// Modular inverse of a mod m (only if g == 1):
long long inv = (x % m + m) % m;