#include <stdio.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) {
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) {
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];
}
int main() {
int a, b, s;
int d, x, y;
int t;
if (a < b) { t = a; a = b; b = t; }
LinearDiophantine(a, b, &d, &x, &y);
printf("(%d)a + (%d)b = %d\n", x
, y
, d
); if (s != d) {
if (s % d == 0) {
printf("(%d)a + (%d)b = %d\n", x
* (s
/ d
), y
* (s
/ d
), s
); } else {
}
}
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)
*/
I2luY2x1ZGUgPHN0ZGlvLmg+CgpzdHJ1Y3QgTWF0cml4MiB7CiAgaW50IG1bMl1bMl07Cn07Cgp2b2lkI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