您的位置:首页 > 其它

中国剩余定理模板

2018-02-02 11:46 330 查看
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll m[10],a[10],b[10];
/*
当 a[0],a[1],...a
互质时
a[i]除数,b[i]是余数,x是最小的解,X是通解
x%a[i]=b[i];
X=x+i*(a[0]*a[1]***a
);
通解即为特解加上所有数之积的任意公倍数。
当 a[0],a[1],...a
不互质时,需要合并方程组
*/

void exgcd(ll a,ll b,ll &x,ll &y){
if(!b) {
x=1,y=0;
}else {
exgcd(b,a%b,y,x);
y-=a/b*x;
}
}

int main(){
ll n,sum=1;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i]>>b[i];
sum*=a[i];
}
ll x,y,S=0;
for(int i=0;i<n;i++){
ll tp=sum/a[i];
exgcd(tp,a[i],x,y);
S+=tp*x*b[i]%sum;
}
S=(S+sum)%sum;
cout<<S<<endl;
}




poj
1006 Biorhythms (中国剩余定理模板)

http://poj.org/problem?id=1006

#include<iostream>
using namespace std;
typedef long long ll;
ll a[3],b[3];

void exgcd(ll a,ll b,ll &x,ll &y){
if(!b) x=1,y=0;
else exgcd(b,a%b,y,x),y-=a/b*x;
}

int main(){
ll c,d,e,f,t=1;
a[0]=23,a[1]=28,a[2]=33;
while(cin>>c>>d>>e>>f){
if(c==-1&&d==-1&&e==-1&&f==-1) break;
b[0]=c,b[1]=d,b[2]=e;
ll m=23*28*33,x,y,ans=0;
for(int i=0;i<3;i++){
ll tp=m/a[i];
exgcd(tp,a[i],x,y);
ans=ans+tp*x*b[i]%m;
}
ans=(ans+m)%m;
while(ans<=f) ans=ans+m;
cout<<"Case "<<t++<<": the next triple peak occurs in "<<ans-f<<" days."<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: