1061

/*
	(x+m*s)-(y+n*s) = k*L (k=0,1,2,...)
	(x-y) + (m-n)*s = k*L
	k*L + (n-m)*s = (x-y) 
	这是个方程,如果有解的话。可以使用扩展的欧几里得算法来求

	对扩展欧几里得写个小节:
	a*x+b*y = gcd(a,b) . 求解这个方程的解,一般用扩展欧几里得算法来解
	首先右边必须是gcd(a,b)的倍数才行,否则无解
	两边同时除以gcd(a,b);
	a'*x+b'*y = 1;
	这样就可以用extGcd来解了,此时a'与b'互质

	int extGcd(int a',int b',int &x,int &y)
	{
		if(b'==0)
		{
			x = 1;
			y = 0;
			return a';
		}
		int r = extGcd(b',a'%b',x,y);
		int t = x;
		x = y;
		y = t-a/b*y;
		return r;
	}

	对于这个解法做点解释,加入有 a'*x'+b'*y' = 1成立
	那么a' = b,b' = a%b = a-a/b*b;代入上式则有
	b*x' + (a-a/b*b)*y' = 1
	a*y' + b*(x'-a/b*y') = 1
    那么由x',y'退出现在的x,y就是
	x = y'
	y = x'-a/b*y';
	非常的完美,就可以把最终的解求出来了

	求出解之后,这只是个一般解 x0,y0
	x = x0 + b*t
	y = y0 - a*t

	如果要求y大于0的话,可以使用 y%a;然后在加a就行了
*/

// include file
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <ctime>

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <bitset>

#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <list>
#include <functional>

using namespace std;

// typedef
typedef __int64 LL;

// 
#define read freopen("in.txt","r",stdin)
#define write freopen("out.txt","w",stdout)

#define Z(a,b) ((a)<<(b))
#define Y(a,b) ((a)>>(b))

const double eps = 1e-6;
const double INFf = 1e100;
const int INFi = 1000000000;
const LL INFll = (LL)1<<62;
const double Pi = acos(-1.0);

template<class T> inline T sqr(T a){return a*a;}
template<class T> inline T TMAX(T x,T y)
{
	if(x>y) return x;
	return y;
}
template<class T> inline T TMIN(T x,T y)
{
	if(x<y) return x;
	return y;
}
template<class T> inline T MMAX(T x,T y,T z)
{
	return TMAX(TMAX(x,y),z);
}
template<class T> inline T MMIN(T x,T y,T z)
{
	return TMIN(TMIN(x,y),z);
}
template<class T> inline void SWAP(T &x,T &y)
{
	T t = x;
	x = y;
	y = t;
}


// code begin
LL x,y,m,n,L,a,b,c,d;

LL gcd(LL f,LL s)
{
	if(s==0) return f;
	return gcd(s,f%s);
}
LL extGcd(LL a1,LL b1,LL &x1,LL &y1)
{
	if(b1==0)
	{
		x1 = 1;
		y1 = 0;
		return a1;
	}
	LL r = extGcd(b1,a1%b1,x1,y1);
	LL t = x1;
	x1 = y1;
	y1 = t - a1/b1*y1;
	return r;
}
int main()
{
	read;
	write;
	while(scanf("%I64d %I64d %I64d %I64d %I64d",&x,&y,&m,&n,&L)!=-1)
	{
		//k*L + (n-m)*s = (x-y) 
		if(x>y) 
		{
			SWAP(x,y);
			SWAP(m,n);
		}
		a = L;
		b = n-m;
		c = x-y;
		d = gcd(a,b);
		if(c%d!=0)
		{
			printf("Impossible\n");
		}
		else
		{
			a/=d;
			b/=d;
			c/=d;
			// a*x+b*y=1的一组解然后 x*c y*c是等于c的一组解
			extGcd(a,b,x,y);
			//printf("%I64d %I64d\n",c,y);
			y *= c;
			y%=a;
			if(y<0) y+=a;
			printf("%I64d\n",y);
		}
	}
	return 0;
}

posted @ 2011-04-29 23:02  AC2012  阅读(160)  评论(0编辑  收藏  举报