快速幂运算, 快速幂取模运算,及慢速乘法

1.快速幂运算

求x的n次方, 或其对mod求模的问题用到快速幂运算, 代码如下非常简单, 这里做一点解释


typedef long long ll;
ll mod_pow(ll x, ll n)
{
	ll ans = 1, base = x;
	while(n > 0)
	{
		if(n & 1) ans = ans * base;//若n的二进制最低位是1, ans需要乘上base
		base = base * base;
		n >>= 1; //n二进制右移
	}
	return ans;
}



解释
例如x^22 = x ^ 16 * x ^ 4 * x ^ 2(22 的二进制是10110)
都可以做如上转换
带入上面代码, 首先n的二进制尾数为0, 不进行ans * base运算,
接下来base = x * x, n右移。
n二进制尾数是1 ans = ans * base, 一步步过去, ans陆续乘上x的二, 四, 十六次方, 函数返回最终结果。

2.对于快速幂后求模的添加一点即可



typedef long long ll;
ll mod_pow(ll x, ll n, ll mod)
{
	ll ans = 1, base = x;
	while(n > 0)
	{
		if(n & 1) ans = ans * base % mod;//若n的二进制最低位是1, res作为最终结果需要乘上x
		base = base * base % mod;
		n >>= 1; //n二进制右移
	}
	return ans;
}

3.慢速乘法
若数据过大可以看到ans * base会爆long long 的内存, 因为是先乘后求模,所以需要使得ans * base在mod的范围内, 这里就用到了慢速乘法。

ll mul(ll a, ll b, ll mod)
{
	ll ans  = 0, base = a;
	while(b)
	{
		if(b & 1) ans = (ans + base) % mod;
		base = (base + base) % mod;
		b >>= 1;
	}

	return ans;
}

ll mod_pow(ll x, ll n, ll mod)
{
	ll ans  = 1, base = x % mod;
	while(n)
	{
		if(n & 1) ans = mul(ans, base, mod);				//慢乘, 其原理和快速幂相似。
		base = mul(base, base, mod);
		n >>= 1;
	}

	return ans;
}

牛客小白月赛12:B. 华华教月月做数学传送门


#include<iostream>
#include<set>
#include<cstdio>
#include<algorithm>
using namespace std;

typedef long long ll;

ll mul(ll a, ll b, ll mod)
{
	ll ans  = 0, base = a;
	while(b)
	{
		if(b & 1) ans = (ans + base) % mod;
		base = (base + base) % mod;
		b >>= 1;
	}

	return ans;
}

ll mod_pow(ll x, ll n, ll mod)
{
	ll ans  = 1, base = x;
	while(n)
	{
		if(n & 1) ans = mul(ans, base, mod);
		base = mul(base, base, mod);
		n >>= 1;
	}

	return ans;
}

int main()
{
	int t;
	scanf("%d", &t);
	while(t--)
	{
		ll a, b, p;
		scanf("%lld %lld %lld", &a, &b, &p);
		printf("%lld\n", mod_pow(a, b, p));
	}
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值