#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
int n,m;
vector<int>a,b;
void exgcd(long long a,long long b,long long &x,long long &y){
if(!b) x=1,y=0;
else
exgcd(b,a%b,y,x),
y-=a/b*x;
}
long long CRT(int siz,long long a[],long long b[]){ // x % b == a
long long M=1;
for(int i=0;i<siz;i++) M*=b[i];
long long ret=0,x,y,tmp;
for(int i=0;i<siz;i++)
{
tmp=M/b[i];
exgcd(tmp,b[i],x,y);
ret=(ret+tmp*x*a[i]%M)%M;
}
return ret=(ret+M)%M;
}
int main(){
long long b[3]={3,5,7},a[3];
for(int i=0;i<=2;i++) scanf("%lld",&a[i]);
long long ans=CRT(3,a,b);
if(ans<10 || ans>100) printf("no answer");
else printf("%lld",ans);
}
扩展中国剩余定理:
适用范围极广,还短小精悍,时间复杂度可以接受:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cctype>
#define maxn 100005
#define LL long long
using namespace std;
int n;
LL X,a,b,m;
void exgcd(LL a,LL b,LL &x,LL &y,LL &gcd)
{
if(!b) x=1,y=0,gcd=a;
else
exgcd(b,a%b,y,x,gcd),
y-=a/b*x;
}
LL mul(LL a,LL b,LL mod)
{
a%=mod , b%=mod;
return ((a*b-(LL)((long double)a/mod*b+1e-7)*mod)%mod+mod)%mod;
}
int main()
{
scanf("%d",&n);
m=1;
for(int i=1;i<=n;i++)
{
scanf("%lld%lld",&a,&b);
/*
x + t * m = b mod a
t * m = b - x mod a
*/
LL x,y,gcd,M;
exgcd(m,a,x,y,gcd);
M=m/gcd*a;
X=(mul(mul(x,(b-X)/gcd,a),m,M)+X)%M;
m=M;
}
printf("%lld\n",X);
}