HDOJ-1788 Chinese remainder theorem again(数论)

就是求模线性方程组

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;

// X % m[i] = a[i]
int m[100], a[100];


//计算 ax+by=gcd(a,b),返回gcd值,求出xy  
LL Ex_gcd(LL a, LL b, LL &x, LL &y)
{
	LL d;
	if (a == 0 && b == 0) return -1;// 无GCD  
	if (b == 0)
	{
		x = 1;
		y = 0;
		return a;
	}
	d = Ex_gcd(b, a%b, y, x);
	y -= a / b * x;
	return d;
}

//解同余方程
bool solve(LL &m0, LL &a0, LL m, LL a)
{
	LL x, y;
	LL g = Ex_gcd(m0, m, x, y);
	if (abs(a - a0) % g) return false;
	x *= (a - a0) / g;
	x %= m / g;
	a0 = (x * m0 + a0);
	m0 *= m / g;
	if (a0 < 0) a0 += m0;
	return true;
}


/*
返回值代表是否有解
解X=a0+k*m0,k为整数
0<=a0<m0
*/
bool MLES(LL &m0, LL &a0, LL n)
{
	int i;
	bool flag = true;
	m0 = 1;
	a0 = 0;
	for (i = 0; i < n; i++)
		if (!solve(m0, a0, m[i], a[i]))
		{
			flag = false;
			break;
		}
	return flag;
}

void work(int n, LL ai)
{
	LL i, j, k, t, mm, aa;
	for (i = 0; i < n; i++)
	{
		scanf("%I64d", &t);
		m[i] = t;
		a[i] = t - ai;
	}
	MLES(mm, aa, n);
	printf("%I64d\n",aa);

}


int main()
{
	int n;
	LL  ai;
	while (scanf("%d%I64d", &n, &ai), n + ai)
		work(n, ai);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值