Elementary Number Theory - Extended Euclid Algorithm
Time Limit : 1 sec, Memory Limit : 65536 KB
Japanese version is here
Extended Euclid Algorithm
Given positive integers a and b, find the integer solution (x, y) to ax+by=gcd(a,b), where gcd(a,b) is the greatest common divisor of a and b.
Input
a b
Two positive integers a and b are given separated by a space in a line.
Output
Print two integers x and y separated by a space. If there are several pairs of such x and y, print that pair for which |x|+|y| is the minimal (primarily) and x ≤ y (secondarily).
Constraints
- 1 ≤ a, b ≤ 109
Sample Input 1
4 12
Sample Output 1
1 0
Sample Input 2
3 8
Sample Output 2
3 -1
#include <bits/stdc++.h> #define fread_siz 1024 inline int get_c(void)
{
static char buf[fread_siz];
static char *head = buf + fread_siz;
static char *tail = buf + fread_siz; if (head == tail)
fread(head = buf, , fread_siz, stdin); return *head++;
} inline int get_i(void)
{
register int ret = ;
register int neg = false;
register int bit = get_c(); for (; bit < ; bit = get_c())
if (bit == '-')neg ^= true; for (; bit > ; bit = get_c())
ret = ret * + bit - ; return neg ? -ret : ret;
} int exgcd(int a, int b, int &x, int &y)
{
if (!b)
{
x = ;
y = ;
return a;
}
int ret = exgcd(b, a%b, y, x);
y = y - x * (a / b);
return ret;
} signed main(void)
{
int x, y;
int a = get_i();
int b = get_i();
exgcd(a, b, x, y);
printf("%d %d\n", x, y);
}
@Author: YouSiki