中国剩余定理(构造)

参考博客

中国剩余定理:

m1,m2,,mn 是两两互质的整数。
M=i=1nmi
Mi=M/mi
tiMimodmi 下的逆元。
对于任意 n 个整数 a1,a2,,an 方程组

{xa1 (modm1)xa2 (modm2)   xan (modmn)

的解为 x=i=1naiMiti

Mi=M/mi

Mi 是除 mi 之外所有模数的倍数

k!=i,aiMiti0 (modmk)

aiMitiai (modmi)

x=i=1naiMiti​ 可使其成立

模板:

代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 12;
typedef long long LL;
LL a[maxn], m[maxn];

void exgcd(LL a1, LL b, LL& x, LL& y)
{
	if(b){
		exgcd(b, a1%b, y, x);
		y -= (a1/b)*x;
		return ;
	}
	x = 1;
	y = 0;
	return ;
}

LL CRT(LL a[], LL m[], int n)
{
	LL M=1, ans=0, Mi, x, y;
	for(int i=1; i<=n; ++i)
		M *= m[i];
	for(int i=1; i<=n; ++i)
	{
		Mi = M/m[i];
		exgcd(Mi, m[i], x, y); // 求出 Mi 在 模 mi意义下的乘法逆元 
		x = (x%m[i] + m[i]) % m[i]; 
		ans = (ans + a[i]*x*Mi) % M;
	}
	return (ans+M) % M; // 求出最小非负整数解 
}

int main()
{
	int n;
	scanf("%d", &n);
	for(int i=1; i<=n; ++i)
		scanf("%lld%lld", &m[i], &a[i]); // mi是模数, ai是是在模 mi 意义下的同余数 
	LL ans = CRT(a, m, n);
	printf("%lld\n", ans);
}

 

posted @   programmingysx  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示