扩展欧几里德
青蛙的约会
附上大佬原文http://www.cnblogs.com/yueshuqiao/archive/2011/08/23/2150960.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 #define LL long long 5 int a,b,v1,v2,p; 6 void exgcd(LL a,LL b,LL &d,LL &x,LL &y) 7 { 8 if(!b){d=a;x=1;y=0;} 9 else { exgcd(b,a%b,d,y,x); y-=x*(a/b);} 10 } 11 12 int main() 13 { 14 while(scanf("%d%d%d%d%d",&a,&b,&v1,&v2,&p)!=EOF) 15 { 16 int c=a-b; 17 LL d,x,y; 18 exgcd(v2-v1,p,d,x,y); 19 if(c%d) 20 { 21 puts("Impossible"); 22 continue; 23 } 24 LL ans=c/d*x; 25 LL r=p/d; 26 ans=(ans%r+r)%r; 27 printf("%lld\n",ans); 28 } 29 }
学到了非递归版,应该就是递推回去,不是很理解
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 #define LL long long 5 int a,b,v1,v2,p; 6 LL exgcd(LL a,LL &x, LL b, LL &y) 7 { 8 LL x1=0,y1=1,x0=1,y0=0; 9 LL r=(a%b+b)%b; 10 LL q=(a-r)/b; 11 x=0;y=1; 12 while(r) 13 { 14 x=x0-q*x1; 15 y=y0-q*y1; 16 x0=x1;y0=y1; 17 x1=x;y1=y; 18 a=b;b=r; 19 r=a%b;q=(a-r)/b; 20 } 21 return b; 22 } 23 int main() 24 { 25 while(scanf("%d%d%d%d%d",&a,&b,&v1,&v2,&p)!=EOF) 26 { 27 LL x,y; 28 LL g=exgcd(v2-v1,x,p,y); 29 if((a-b)%g) 30 { 31 puts("Impossible"); 32 continue; 33 } 34 x=(a-b)/g*x; 35 LL r=p/g; 36 x=(x%r+r)%r; 37 printf("%lld\n",x); 38 } 39 }