First recommend a blog I saw: Link: Personal Understanding---Extended Euclid's Theorem-Watermelon Does Not Understand the Acid of Lemon- Blog Garden http://www.cnblogs.com/zhengguiping--9876/p/ 5308276.html
It is recommended to read the following first, and then read the blog above.
From our seniors:
Bezu's equation:
c=gcd(a,b)
When d is a multiple of c
ax+by=d always has an integer solution
Among all solutions, there is one and only one solution ( x,y ) that satisfies -b<=x<=b,-a<=y<=a
Extended Euclidean Algorithm:
When finding c=gcd(a,b) , simultaneously find Bezu's equation: an integer solution of ax+by=c (so the expansion has five parameters)
Principle demonstration:
Find the solution for 18x+5y=1
18%5=3,18=5*3+3,3=18+5*(-3)
5%3=2,5=3*1+2,2=5+3*(-1)
3%2=1,3=2*1+1,1=3+2*(-1)
Then proceed from bottom to top
1=3+2*(-1)
1=3+(5+3*(-1))*(-1) ( substitute into the second formula )
=3*2+5*(-1)
1=(18+5*(-3))*2+5*(-1) ( substitute into the first formula )
=18*2+5*(-7)
Then (2,-7) is a solution
It is recommended that you choose a few data and calculate it yourself
ll exgcd(ll a,ll b,ll& d,ll& x,ll& y)
{
if(!b){d=a,x=1,y=0;}
else
{
exgcd(b,a%b,d,y,x);
y-=x*(a/b);
}
}