reference:http://www.cnblogs.com/ka200812/archive/2011/09/02/2164404.html
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 114194 | Accepted: 23374 |
Description
Input
Output
Sample Input
1 2 3 4 5
Sample Output
4
Source
(x+mt) % L - (y+nt) % L = 0
[ (x+mt) - (y+nt) ] % L = 0
(x+mt) - (y+nt) = k*L, k∈N
t*(n-m) + k*L = x-y
a*x + b*y = c,其中a=n-m,b=L,c=x-y。
# include
# include
# define LL long long
using namespace std;
LL X, Y, M, N, L;
LL x, y, a, b, c, d;
LL ex_gcd(LL a, LL b)
{
LL t;
if(b == 0)
{
x = 1;
y = 0;
return a;
}
d = ex_gcd(b, a%b);
t = x;
x = y;
y = t-(a/b)*y;
return d;
}
int main()
{
while(~scanf("%lld%lld%lld%lld%lld",&X,&Y,&M,&N,&L))
{
a = N-M;
b = L;
c = X-Y;
d = ex_gcd(a, b);
if(c % d != 0)
{
puts("Impossible");
continue;
}
x = x*c/d;
y = y*c/d;
LL k = x*d/b;
k = x - b*k/d;
if(k < 0)
k += b/d;//x可能为负数,这时候要加上b/d才为非负数。
printf("%lld\n",k);
}
return 0;
}