跳到正文

个人记录

P4777 【模板】扩展中国剩余定理(EXCRT)

yqzx0307约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年6月14日
收录
2026年6月25日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
#define int __int128
constexpr int maxn=1e5;
int t;
int n;
int m;
int mi[maxn];
int ai[maxn];
void read(int *t)
{
    int f=1;
    int x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    (*t)=x*f;
}
void write(int x)
{
    if(x<0)
    {
        putchar('-');
        x=-x;
    }
    if(x>9)
    {
        write(x/10);
    }
    putchar(x%10+'0');
    return;
}
int ex_gcd(int a,int b,int &x,int &y)
{
    if(!b)
    {
        x=1,y=0;
        return a;
    }
    int ret=ex_gcd(b,a%b,y,x);
    y-=a/b*x;
    return ret;
}
int a,b,x,y;
int A=1,B;
signed main()
{
    read(&n);
    for(int i=1;i<=n;++i)
    {
        read(&a);
        read(&b);
        int g=ex_gcd(A,a,x,y);
        x=(B-b)/g*x;
        B-=A*x;
        A=a/g*A;
        B=(B%A+A)%A;
    }
    int ans=(B%A+A)%A;
    write(ans);
    return 0;
}

https://www.luogu.com.cn/problem/P4777

原文