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

本文介绍了一种解决特定数学问题的方法,即如何从一系列同余方程中找到非负整数解。通过使用扩展欧几里得算法,文章详细解释了如何逐步合并这些方程并求解未知数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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); 
}
}
在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值