#include <pari/pari.h>

/* return d = gcd(a,b), sets u, v such that au + bv = gcd(a,b) */
GEN
extgcd(GEN A, GEN B, GEN *U, GEN *V)
{
  pari_sp av = avma;
  GEN ux = gun, vx = gzero, a = A, b = B;
  if (typ(a) != t_INT || typ(b) != t_INT) err(typeer, "extgcd");
  if (signe(a) < 0) { a = negi(a); ux = negi(ux); }
  while (!gcmp0(b))
  {
    GEN r, q = dvmdii(a, b, &r), v = vx;

    vx = subii(ux, mulii(q, vx));
    ux = v;
    a = b; b = r;
  }
  *U = ux;
  *V = diviiexact( subii(a, mulii(A,ux)), B );
  gerepileall(av, 3, &a, U, V); return a;
}

int
main()
{
  GEN x, y, d, u, v;
  pari_init(1000000,2);
  printf("x = "); x = lisGEN(stdin);
  printf("y = "); y = lisGEN(stdin);
  d = extgcd(x, y, &u, &v);
  pariputsf("gcd = %Z\nu = %Z\nv = %Z\n", u,v);
  return 0;
}