poj之旅——2429,3641,1995

本文介绍快速幂算法及其在费马小定理中的应用,包括快速幂乘法、指数运算以及素数判断等核心实现。通过具体题目示例展示了如何高效地解决涉及大数幂运算的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

快速幂

3641:费马小定理,快速幂加素数判断。

1995:求几个数的幂的和的模。

2429:给出LCM和GCD,逆推a和b,巨疯狂,数据量极大,模拟过不了,可以借鉴此。

模拟型题。

参考程序:

3641:

#include <iostream>
using namespace std;
typedef long long LL;
LL mod_mult(LL a, LL b, LL m)
{
	LL res = 0;
	LL exp = a % m;
	while (b)
	{
		if (b & 1)
		{
			res += exp;
			if (res > m) res -= m;
		}
		exp <<= 1;
		if (exp > m) exp -= m;
		b >>= 1;
	}
	return res;
}
LL mod_exp(LL a, LL b, LL m) 
{
	LL res = 1;
	LL exp = a % m;
	while (b)
	{
		if (b & 1) res = mod_mult(res, exp, m);
		exp = mod_mult(exp, exp, m);
		b >>= 1;
	}
	return res;
}
bool is_prime(const int& n)
{
	for (int i = 2; i * i <= n; ++i)
	{
		if (n % i == 0)
		{
			return false;
		}
	}
 
	return n != 1;	
}
int main()
{
	int p, a;
	while (cin >> p >> a && p && a)
	{
		if (!is_prime(p) && (mod_exp(a, p, p) == a))
		{
			cout << "yes" << endl;
		}
		else
		{
			cout << "no" << endl;
		}
	}
	return 0;
}

1995:

#include <iostream>
using namespace std;
 
typedef long long LL;
 
LL mod_mult(LL a, LL b, LL m)
{
	LL res = 0;
	LL exp = a % m;
	while (b)
	{
		if (b & 1)
		{
			res += exp;
			if (res > m) res -= m;
		}
		exp <<= 1;
		if (exp > m) exp -= m;
		b >>= 1;
	}
	return res;
}
LL mod_exp(LL a, LL b, LL m) {
	LL res = 1;
	LL exp = a % m;
	while (b)
	{
		if (b & 1) res = mod_mult(res, exp, m);
		exp = mod_mult(exp, exp, m);
		b >>= 1;
	}
	return res;
}
int main(int argc, char *argv[])
{
	int Z;
	cin >> Z;
	while (Z--)
	{
		int M, H;
		cin >> M >> H;
		int ans = 0;
		while (H--)
		{
			int A_i, B_i;
			cin >> A_i >> B_i;
			ans += mod_exp(A_i, B_i, M);
		}
		ans %= M;
		cout << ans << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值