#include <stdio.h>
#include <math.h>

struct Matrix2 {
  int m[2][2];
};

void setMatrix(struct Matrix2 *M, int a, int b, int c, int d) {
  M->m[0][0] = a;
  M->m[0][1] = b;
  M->m[1][0] = c;
  M->m[1][1] = d;
}

void setMatrixE(struct Matrix2 *M) { setMatrix(M, 1, 0, 0, 1); }

struct Matrix2 calcMatrixMul(struct Matrix2 A, struct Matrix2 B) {
  struct Matrix2 C;
  C.m[0][0] = A.m[0][0] * B.m[0][0] + A.m[0][1] * B.m[1][0];
  C.m[0][1] = A.m[0][0] * B.m[0][1] + A.m[0][1] * B.m[1][1];
  C.m[1][0] = A.m[1][0] * B.m[0][0] + A.m[1][1] * B.m[1][0];
  C.m[1][1] = A.m[1][0] * B.m[0][1] + A.m[1][1] * B.m[1][1];
  return C;
}

void vomitMatrix2(struct Matrix2 M) {
  printf("(%d, %d, %d, %d)\n",
         M.m[0][0],
         M.m[0][1],
         M.m[1][0],
         M.m[1][1]);
}

void LinearDiophantine(int a, int b, int *d, int *x, int *y, int *alpha, int *beta) {
  struct Matrix2 M, A;
  int k, r;
  setMatrixE(&M);
  for (;;) {
    k = a / b;
    r = a % b;
    setMatrix(&A, 0, 1, 1, -k);
    M = calcMatrixMul(A, M);
/*
    printf("(%d, %d) = (%d, %d) : %d\n", a, b, b, r, k);
    vomitMatrix2(M);
*/
    if (r == 0)
      break;
    a = b;
    b = r;
  }
  *d  = b;
  *x = M.m[0][0];
  *y = M.m[0][1];
  *alpha = M.m[1][0];
  *beta = M.m[1][1];
}

int eval(int x, int y) { return abs(x * y); }

void reduction(int x, int y, int alpha, int beta, int *x_best, int *y_best) {
  int init_point, best_point, now_point, direction;
  *x_best = x; *y_best = y;
  init_point = best_point = eval(x, y);
  if (init_point > eval(x + alpha, y + beta))
    direction = +1;
  else
    direction = -1;
  while ((now_point = eval(x += (direction * alpha), y += (direction * beta))) < init_point) {
/*    printf("x = %d, y = %d\n", x, y); */
    if (now_point < best_point) {
      best_point = now_point;
      *x_best = x; *y_best = y;
    }
  }
}

int main() {
  int a, b, s;
  int d, x, y, alpha, beta;
  int x_best, y_best;
  printf("a = "); scanf("%d", &a); putchar('\n');
  printf("b = "); scanf("%d", &b); putchar('\n');
  printf("s = "); scanf("%d", &s); putchar('\n');
  LinearDiophantine(a, b, &d, &x, &y, &alpha, &beta);
  if (d < 0) {
    x *= -1; y *= -1; d *= -1;
  }
  printf("(%d)a + (%d)b = %d\n", x, y, d);
  if (s != d) {
    if (s % d == 0) {
      x = x * s / d;
      y = y * s / d;
      reduction(x, y, alpha, beta, &x_best, &y_best);
      printf("(%d)a + (%d)b = %d\n", x_best, y_best, s);
    } else {
      printf("no solution.\n");
    }
  }  
  return 0;
}
/* end */
/* ref. http://w...content-available-to-author-only...o.jp/dp/4314001658/ chapter.1-3
 *      http://w...content-available-to-author-only...o.jp/dp/4000076345/ chapter.7(2)
 */
