扩展欧几里得

http://acm.hnu.cn/online/?action=problem&type=show&id=12831&courseid=268

#include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;

long long extend_gcd(long long a,long long b,long long &x,long long &y)
{
	if (b==0)
	{
		x=1;y=0;
		return a;
	}
	else
	{
		int r=extend_gcd(b,a%b,y,x);
		y-=x*(a/b);
		return r;
	}
}

int main()
{
	int T;
	scanf("%d",&T);
	while (T--)
	{
		long long n1,f1,d1,n2,f2,d2;
		scanf("%lld%lld%lld%lld%lld%lld",&n1,&f1,&d1,&n2,&f2,&d2);

		long long x0,y0;
		long long xx=extend_gcd(d1,-d2,x0,y0);
		if ((f2-f1)%xx)
			printf("0\n");
		else
		{
			long long k=(f2-f1)/xx;
			x0*=k;
			y0*=k;
			long long g=abs(-d1*d2/xx);
			long long p1=g/d1;
			long long p2=g/d2;

			if (x0-p1>=0 && y0-p2>=0)
			{
				long long num1=x0/p1;
				long long num2=y0/p2;
				long long nnn=num1<num2?num1:num2;
				x0-=nnn*p1;
				y0-=nnn*p2;
			}
			else if (x0<0 || y0<0)
			{
				long long num1=(x0+1)/p1;
				long long num2=(y0+1)/p2;
				long long nnn=num1<num2?num1:num2;
				x0+=(-nnn+1)*p1;
				y0+=(-nnn+1)*p2;
			}
			if (x0>n1-1 || y0>n2-1)
			{
				printf("0\n");
				continue;
			}
			long long total1=n1-1-x0;
			long long total2=n2-1-y0;
			long long num1=total1/p1+1;
			long long num2=total2/p2+1;
			printf("%lld\n",num1<num2?num1:num2);
		}
	}
}


你可能感兴趣的:(扩展欧几里得)