洛谷 P3868 [TJOI2009]猜数字(中国剩余定理, 快速乘法)

中国剩余定理, 快速乘法
本题要点:
1、 套用 中国剩余定理 模板,但是注意,这里的 乘法会 爆 long long ,因此,
用快速乘法来代替。
2、 a[i] <= 10^9, 当计算 某数 z 和 a[i] 相乘, 应该是调用 quick_multi(a[i], z, mod),
也就是用 a[i] 去依次乘上 z 的 二进制的每一位。(a[i] 数值较大, z的较小)

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MaxK = 20;
typedef long long ll;
ll m[MaxK], a[MaxK];
int k;
ll b[MaxK];

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

ll quick_multi(ll x, ll y, ll mod)
{
	ll ans = 0;
	while(y)
	{
		if(y & 1)
		{
			ans = (ans + x) % mod;
		}
		x = (x + x) % mod;
		y >>= 1;
	}
	return ans;
}

ll crt()
{
	int n = k;
	ll mm = 1, res = 0;
	for(int i = 1; i <= n; ++i)
	{
		mm *= m[i];	
	}
	for(int i = 1; i <= n; ++i)
	{
		ll x, y;	// m[i] * y + mm / m[i] * x = 1
		exgcd(mm / m[i], m[i], x, y);
		x = (x % m[i] + m[i]) % m[i]; // 这里x化为 小于m[i] 的整数
		b[i] = quick_multi(mm / m[i], x, mm);
		res = (res + quick_multi(a[i], b[i], mm)) % mm;
	}
	return (res % mm + mm) % mm;
}

int main()
{
	scanf("%d", &k);
	for(int i = 1; i <= k; ++i)
	{
		scanf("%lld", &a[i]);
	}
	for(int i = 1; i <= k; ++i)
	{
		scanf("%lld", &m[i]);
	}
	printf("%lld\n", crt());
	return 0;
}

/*
3
1 2 3
2 3 5
*/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值