Chinese Remainder Theorem

用于求解同余方程组

x = ri (mod ai)   1<=i<=n

更一般的,我们来考虑如何解决ai不互质的情况

我们可以用合并方程组的方法来解决此类问题。

x = r1 (mod a1)

x = r2 (mod a2)

我们可以将上述方程写成另一种形式

x = k1*a1+r1

x = k2*a2+r2

我们可以得到

k1*a1+r1=k2*a2+r2

k1*a1 = r2-r1 (mod a2)

用扩展欧几里得可以求出k1

(程序中先默认求出k1*a1 = gcd(a1,a2)(mod a2) 的解,再求出k1 = k1'*( (r2-r1)/gcd ),过去这地方一直没看懂,擦擦擦 )

那么我么可以得到 x,方程组可以被合并成

x = (k1*a1+r1) (mod  a1*a2/gcd )

不断合并即可求解

献上入门题

hdu3579

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
int Case,n;
LL m1,r1,m2,r2,x,y;
LL m[100],r[100];

LL exgcd(LL a,LL b){
  if (b==0){
      x = 1; y = 0;
      return a;
  }
  LL ret = exgcd(b,a%b);
  LL tmp = x;
  x = y; y = tmp-(a/b)*y;
  return ret;
}

int main(){
  scanf("%d",&Case);
  for (int T=1;T<=Case;T++){
      scanf("%d",&n);
      for (int i=1;i<=n;i++)
        scanf("%I64d",&m[i]);
      for (int i=1;i<=n;i++)
        scanf("%I64d",&r[i]);
      m1 = m[1]; r1 = r[1];
      bool flag = 0;
      for (int i=2;i<=n;i++){
        m2 = m[i];
        r2 = r[i];
        int d = exgcd(m1,m2);
        int c = r2-r1;
        if (c%d){
            flag = 1;
            break;
        }
        int t = m2/d;
        x = (x*(c/d)%t+t)%t;
        r1 = x*m1+r1;
        m1 = m1*m2/d;
      }
      if (flag) {printf("Case %d: -1\n",T);continue;}
      if (r1<=0) r1+=m1;
      printf("Case %d: %I64d\n",T,r1);
  }
  return 0;
}

poj2891

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
int n;
LL x,y,m1,m2,r1,r2;

LL exgcd(LL a,LL b){
  if (b==0){
  	x = 1; y = 0;
  	return a;
  }
  LL ret = exgcd(b,a%b);
  LL tmp = x;
  x = y; y = tmp-(a/b)*y;
  return ret;
}

int main(){
  while (~scanf("%d",&n)){
  	scanf("%lld%lld",&m1,&r1);
  	bool flag = 0;
  	for (int i=1;i<n;i++){
  	  scanf("%lld%lld",&m2,&r2);
  	  if (flag) continue;
  	  LL d = exgcd(m1,m2);
  	  LL c = r2-r1;
  	  if (c%d) {flag=1;continue;}
  	  LL t = m2/d;
  	  x = (x*(c/d)%t+t)%t;
  	  r1 = m1*x+r1;
  	  m1 = m1*m2/d;
  	}
  	if (flag) puts("-1");
  	  else printf("%lld\n",r1);
  }
  return 0;
}


你可能感兴趣的:(crt)