快速幂运算

<span style="color: rgb(51, 51, 51); font-family: arial, 宋体, sans-serif; font-size: 14px; line-height: 24px; text-indent: 28px;">快速幂其时间复杂度为 O(log₂N), 比O(N)提高了很高效率</span>
例如求a的b次幂
则只需要从低位到高位取b的二进制位,是1就乘以a^(2^i-1)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
typedef pair<int, int> P;
typedef long long LL;
#define LOCAL
#define INF 0x3f3f3f3f
#define MAX_N

const int ret = 1e9 + 7;

LL quick_mod(LL a, LL b)
{
    LL ans = 1;
    //对可操作位进行操作
    while(b)
    {
        if(b&1)
            ans = ans*a;
        b >>= 1;
        a = a*a;//2^n
    }
    return ans;
}

int main()
{
	#ifdef LOCAL
		freopen("b:\\data.in.txt", "r", stdin);
	#endif
	//快速幂运算
	cout <<quick_mod(2, 2)<<endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值