nefu84-擴展歐幾里德



題目鏈接:http://acm.nefu.edu.cn/JudgeOnline/problemshow.php?problem_id=84

思路:與上一題很相似,擴展歐幾里得算法。


#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;

typedef long long LL;

LL n, m, ax, by;

void ex_gcd(LL a, LL b, LL &d, LL &x, LL &y)
{
	if(!b)
	{
		d = a; x = 1; y = 0;
	}
	else
	{
		ex_gcd(b, a%b, d, y, x);
		y -= x*(a/b);
	}
}

void read_case()
{
	scanf("%lld%lld%lld%lld", &n, &m, &ax, &by);
}

void solve()
{
	read_case();
	LL d, x, y;
	ex_gcd(m, n, d, x, y);
	if((by-ax) % d) { printf("Impossible\n"); return ;}
	LL b1 = n / d;
	x *= (by-ax) / d;
	LL ans = (x % b1 + b1) % b1;
	printf("%lld\n", ans);
}

int main()
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		solve();
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章