poj2891(线性同余方程 中国剩余定理)

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:
Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.

“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”

Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input
The input contains multiple test cases. Each test cases consists of some lines.

Line 1: Contains the integer k.
Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).
Output
Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

Sample Input
2
8 7
11 9
Sample Output
31
Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

题目意思为让你求一个x,x满足
{x%a1=r1; x=a2y2+r2;
x%a2=r2;-------->x=a1
y1+r1;------------>a1y1-a2y2=r2-r1;(1)
x%a3=r3; x=a3y3+r3; 利用扩展欧几里得求出y1(选最小整数解)

}
由于各个a值不一定互质,所以需要两两合并,即一二式合并成新的方程x%a=r;然后再与第三个式子合并,这样一直合并到最后一个,求出的x即我们所求的,那么新和成的a和r需要满足什么条件呢?
新和成的方程所求的x满足x%a=r,那么这个x同时要满足x%a1=r1,x%a2=r2;
这里直接给出a和r的构造办法r=a1
y1+r1,a=a1a2/gcd(a1,a2)(即a1和a2的最小公倍数)
证明:因为x%a=x%(a1
a2/gcd(a1,a2)=a1y1+r1;
即x=a1
a2/gcd(a1,a2)y+a1y1+r1;
所以x%a1=(a1a2/gcd(a1,a2)+a1y1+r1)%a1=0+r1=r1;
同理 x%a2=r2;(因为a1y1+r1=a2y2+r2;)

ac代码

#include <iostream>
#include<cstdio>
typedef long long int ll;
using namespace std;
long long gcd,ans,temp;
int temp1;
ll edgcd(ll a, ll b, ll &x, ll &y)
{

	if (b == 0)
	{
		x = 1;
		y = 0;
		return a;
	}
	 ans=edgcd(b, a%b, x, y);
	temp = x;
	x = y;
	y = temp - (a / b)*y;
	return ans;
}
ll  cal(ll a, ll b, ll c)//扩展欧几里得算法,用来求二元一次方程解;
{
	ll b0;
	ll x, y;  gcd=edgcd(a, b, x, y);
	
	if (c%gcd) {temp1=0;	
	}//但c与最大公因数不互质时,方程无解。
	else {
		b0 = b / gcd;
		return (x*(c / gcd) % b0 + b0) % b0;
	}
}
int main()
{
	int n;
	ll a1,a2,r1,r2,s;
	while(cin>>n)	
	{
		temp1=1;
		scanf("%lld%lld",&a1,&r1);
		n--;
		while(n--)
	{
		scanf("%lld%lld",&a2,&r2);
		s=cal(a1,a2,r2-r1);
		r1=s*a1+r1;
		a1=a1*a2/gcd;//旧的a1和a2的最小公倍数
		}	
	if(temp1==0)r1=-1;
	printf("%lld\n",r1); 
}
}
在这里插入代码片
发布了109 篇原创文章 · 获赞 35 · 访问量 6029

猜你喜欢

转载自blog.csdn.net/weixin_43965698/article/details/88987858