中国剩余定理(余数定理)Chinese remainder

int		//扩展欧几里得定理 ax + by = gcd(a,b) = r .
Extend_Gcd(int a, int b, int &x, int &y) {
if (!b) {
x = 1; y = 0;
return	a;
}
else {
int r = Extend_Gcd(b, a%b, y, x);//递归直到得出最大公约数r。
y -= a / b*x;
return	r;
}
}

int		//中国剩余定理(余数定理)Chinese remainder
Crt(int a[], int m[], int n ){
int M = 1;
for (int i = 0; i < n; ++i )
M *= m[i];
int ans = 0;
for (int i = 0; i < n; ++i){
int x, y;
int tm = M / m[i];
Extend_Gcd( tm, m[i], x, y);
ans = (ans + tm * x * a[i]) % M;
}
return (ans + M) % M;
}

实战训练:

UVA, 756 BiorhythmsUVA原题链接

本校ACM链接


AC代码,注意,结尾处有个陷阱 就是 res



#include 
#define ll long long
int const N = 3;
ll	a[N], m[N] = { 23,28,33 }, Lcm, D;

//扩展欧几里得定理 ax + by = gcd(a,b) = r .
void gcd(ll a, ll b, ll &d, ll &x, ll &y ){
	if ( !b ) {
		d = a;
		x = 1, y = 0;
	}
	else {
		gcd( b, a%b, d, y, x );
		y -= (a / b)*x;
	}
}
//中国剩余定理(余数定理)Chinese remainder
ll China(int n, ll *m, ll *a){
	ll M = 1, d, y, x = 0;
	for (int i = 0; i



你可能感兴趣的:(初等数论(信安数学))