Strange Way to Express Integers [扩展中国剩余定理]

本文介绍了一种使用中国剩余定理解决特定数学问题的方法,通过一组特定的整数对来表达非负整数,详细解释了如何从这些整数对逆向求解原始数值,包括输入输出格式和示例,以及实现这一算法的C++代码。

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

Description

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


扩展中国剩余定理模板

#include<bits/stdc++.h>
#define LL long long
using namespace std;
LL k,x,y,a,m,ans,lcm,gcd;
void exgcd(LL a,LL b){
	if(!b){x=1,y=0,gcd=a; return;}
	exgcd(b,a%b); LL x1=y,y1=x-a/b*y; x=x1,y=y1;
}
int main(){
	cin>>k>>m>>a;
	ans = a%m , lcm=m;
	for(int i=2;i<=k;i++){
		cin>>m>>a;
		LL c = (a - ans%m + m) % m;
		exgcd(lcm,m); 
		if(c%gcd){printf("-1"); return 0;}
		x = (x * (c/gcd)) % (m/gcd);
		ans += x * lcm; lcm *= (m/gcd);
		ans = (ans%lcm + lcm) % lcm;
	}cout<<ans; return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FSYo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值