FLINT3.7.0-dev

n_xgcd

Synopsis#include <flint/ulong_extras.h>
ulong n_xgcd(ulong * a, ulong * b, ulong x, ulong y)source

Returns g=gcd⁡(x,y)g = \gcd(x, y) and sets *a, *b to unsigned values with ax−by=gax - by = g. Requires x≥yx \ge y.

n_xgcd uses the extended Euclidean algorithm, which always produces cofactors ∣a∣<x/2\lvert a \rvert < x/2 and ∣b∣<x/2\lvert b \rvert < x/2, apart from a few degenerate cases. The proof is by induction. Suppose that at some step xn=qyn+rx_n = q y_n + r with r≥1r \ge 1 and 1=syn−tr1 = s y_n - t r with s<yn/2s < y_n/2 and t<yn/2t < y_n/2. Then 1=syn−t(xn−qyn)=(s+tq)yn−txn1 = s y_n - t (x_n - q y_n) = (s + tq) y_n - t x_n, and it suffices to show s+tq<xn/2s + tq < x_n/2, since t<yn/2<xn/2t < y_n/2 < x_n/2. At the previous step of the back-substitution we had 1=sr−cd1 = s r - c d with s<r/2s < r/2 and c<r/2c < r/2, so s+tq<r/2+qyn/2=(r+qyn)/2=xn/2s + tq < r/2 + q y_n/2 = (r + q y_n)/2 = x_n/2.

Cite this page

The FLINT team, “n_xgcd (ulong_extras.h),” FLINT: Fast Library for Number Theory, documentation, version 3.7.0-dev, 2026. https://flintlib.org/doc/ulong_extras/n_xgcd.html (generated 2026-11-02).