1. 程式人生 > >51 Nod 1079 中國剩余定理(中國剩余定理)

51 Nod 1079 中國剩余定理(中國剩余定理)

html targe () ice using str clu blank space

題目鏈接:https://www.51nod.com/onlineJudge/questionCode.html#problemId=1079&noticeId=350893

題意:一個正整數K,給出K Mod 一些質數的結果,求符合條件的最小的K。

例如,K % 2 = 1, K % 3 = 2, K % 5 = 3。符合條件的最小的K = 23。

題解:裸題,想看證明的可以點擊傳送門

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 typedef long
long LL; 6 const int N=12; 7 LL a[N],m[N]; 8 9 LL e_gcd(LL a,LL b,LL &x,LL &y){ 10 LL d=a; 11 if(b!=0){ 12 d=e_gcd(b,a%b,y,x); 13 y-=(a/b)*x; 14 } 15 else{x=1;y=0;} 16 return d; 17 } 18 19 LL inv(LL t,LL p){ 20 LL x,y; 21 if(e_gcd(t,p,x,y)==1
) return (x%p+p)%p; 22 else return -1; 23 } 24 25 26 //x=a[i](mod m[i]) 27 LL CRT(LL n,LL *a,LL *m){ 28 LL M=1,ans=0; 29 for(int i=0;i<n;i++) M*=m[i]; 30 for(int i=0;i<n;i++){ 31 LL w=M/m[i]; 32 ans=(ans+w*inv(w,m[i])*a[i])%M; 33 } 34 return (ans+M)%M;
35 } 36 37 int main(){ 38 int n; 39 cin>>n; 40 for(int i=0;i<n;i++) cin>>m[i]>>a[i]; 41 cout<<CRT(n,a,m)<<endl; 42 return 0; 43 }

51 Nod 1079 中國剩余定理(中國剩余定理)