基础数论 中国剩余定理
中国剩余定理:#
设
的解为
是除 之外所有模数的倍数
可使其成立
模板:
代码
#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);
}
扩展中国剩余定理:#
与中国剩余定理同样,但
若
:
当且仅当
时有解,用 求得一组解 ,带入方程组中得 。
的通解为 令
,则 这样就把两个同余式换成了一个同余式,以此类推即可求解。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
LL r[maxn], m[maxn];
LL exgcd(LL a, LL b, LL& x, LL& y)
{
if(b){
LL d = exgcd(b, a%b, y, x);
y -= a/b*x;
return d;
}
x = 1; y = 0;
return a;
}
LL quick_mul(LL a, LL b, LL mod)
{
LL ans = 0;
while(b>0){
if(b&1)
ans = (ans + a) % mod;
a = (a << 1) % mod;
b >>= 1;
}
return ans;
}
LL excrt(int n)
{
LL M=m[1], R=r[1], k1, k2;
for(int i=2; i<=n; ++i)
{
LL a=M, b=m[i];
LL c = ((r[i]-R)%b + b) % b;// 求ax+by=c即求ax同余c(mod b),所以mod b对于答案没有影响
LL d = exgcd(a, b, k1, k2);
if(c%d != 0) return -1; // 无解
k1 = quick_mul(k1, c/d, b/d); // 找出方程 ak1+bk2=c的最小非负整数解
R += k1 * M;
M = a/d*b;
R = (R%M + M) % M;
}
return (R%M + M) % M;
}
int main()
{
int n;
scanf("%d", &n);
for(int i=1; i<=n; ++i)
scanf("%lld%lld", &m[i], &r[i]); // m[i] 表示模数, r[i] 表示余数
printf("%lld\n", excrt(n));
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】