http://poj.org/problem?id=1061
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<map> #include<queue> #include<cmath> #define LL long long using namespace std; LL gcd(LL x,LL y) { if(x%y==0) return y; return gcd(y,x%y); } void exgcd(LL a,LL b,LL *x,LL *y) { if(b==0) { *x=1; *y=0; return ; } exgcd(b,a%b,x,y); LL t=*x; *x=*y; *y=(t-(a/b)*(*y)); } int main() { LL x,y,m,n,L; while(cin>>x>>y>>m>>n>>L){ if(m==n) { printf("Impossible\n"); continue; } LL a=n-m; LL b=x-y; LL k=gcd(L,a); if(b%k!=0) { printf("Impossible\n"); }else { LL x1,y1; L/=k; a/=k; b/=k; exgcd(L,a,&x1,&y1); y1*=b; y1=(y1%L+L)%L; cout<<y1<<endl; } } return 0; }