拓展欧几里得例题

一个环,A在x处,B在y处,A与B约定延同一方向走,A每次走m米,B每次走n米,环长L米,问至少他们走几次能碰面,还是永远不能见面?
//扩展欧几里得 
#include<iostream>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
typedef long long ll;
ll ex_gcd(ll a, ll b, ll &x, ll &y){
	if(!b){
		x = 1;
		y = 0;
		return a;
	}
	ll d = ex_gcd(b, a%b, x, y);
	ll t = x;
	x = y;
	y = t - (a/b) * y;
	return d;
} 
void solve(ll a, ll b, ll c){
	ll x, y;
	ll d = ex_gcd(a, b, x, y);	// d是 a,b最大公约数 
	if( c % d ){	//无解情况 
		cout << "Impossible" << endl;
		return ;
	}
	x = x * c / d;	// 求一个解 因为你之前求的  gcd(a,b)的解,所以现在需要乘c。 
	ll t = b / d;
	if(t < 0)
		t = -t;
	x = (x%t + t) % t; //求x的最小正整数解
	cout << x << endl; 
	return ;
}
int main(){
	int x, y, m, n, L;
	while(cin >> x >> y >> m >> n >> L){
		solve(m-n, L, y-x);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/henulmh/article/details/107232725