快速乘/快速幂(+取模)

为什么要用快速乘/快速幂

快速幂

传统的求幂算法时间复杂度非常高(为O(指数n)),因为当指数n非常大的时候,需要执行的循环操作次数也非常大,而快速幂能帮我们以相对更少的时间算出指数非常大的幂。

快速乘

加法比乘法快。可以用较多的加法来取代乘法来减少时间复杂度(乘法分配律?)

原理

见:https://blog.csdn.net/maxichu/article/details/45459715
(绝不承认自己懒)

模板

#include<stdio.h>
#define LL long long
LL mul_mod(LL a,LL b,LL c)   //a*b mod c快速乘
{
    LL ans=0;
    while(b)
    {
        if(b%2)
            ans=(ans+a)%c;
        a=(a+a)%c;
        b/=2;
    }
    return ans;
}
LL pow_mod(LL a,LL b,LL c)   //a^b mod c快速幂
{
    LL res=1;
    a=a%c;
    while(b)
    {
        if(b%2)
            res=(res*a)%c;  //res=mul_mod(res,a,c);更快
        a=(a*a)%c;   //a=mul_mod(a,a,c);更快
        b/=2;
    }
    return res;
}

int main()
{
    LL a,b,c;
    scanf("%lld%lld%lld",&a,&b,&c);
    printf("%lld\n",mul_mod(a,b,c));
    printf("%lld\n",pow_mod(a,b,c));
    return 0;
}

例题

HDU 2035

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#define LL long long
#define INF 0x3f3f3f3f
const int MAX=1e6+50;
using namespace std;

LL pow_mod(LL a,LL b,LL c)
{
    LL res=1;
    a=a%c;
    while(b)
    {
        if(b%2)
            res=(res*a)%c;  //res=mul_mod(res,a,c);
        a=(a*a)%c;   //a=mul_mod(a,a,c);
        b/=2;
    }
    return res;
}
int main()
{
    LL a,b;
    while(~scanf("%lld%lld",&a,&b)&&a!=0&&b!=0)
        printf("%lld\n",pow_mod(a,b,1000));
    return 0;
}

HDU 5187

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#define LL long long
#define INF 0x3f3f3f3f
const int MAX=1e5+50;
using namespace std;

LL mul_mod(LL a,LL b,LL c)   //a*b mod c
{
    LL ans=0;
    while(b)
    {
        if(b%2)
            ans=(ans+a)%c;
        a=(a+a)%c;
        b/=2;
    }
    return ans;
}
LL pow_mod(LL a,LL b,LL c)   //a^b mod c
{
    LL res=1;
    a=a%c;
    while(b)
    {
        if(b%2)
            res=mul_mod(res,a,c);
        a=mul_mod(a,a,c);
        b/=2;
    }
    return res;
}
int main()
{
    long long a,b;
    while(~scanf("%lld%lld",&a,&b))
    {
        if(a==1)        //此处需对1特判
        {
            if(b==1)
                printf("0\n");
            else
                printf("1\n");
            continue;
        }
        printf("%lld\n",(pow_mod(2,a,b)-2+b)%b);
    }
    return 0;
}

注意到模板中快速幂函数的这两行

         if(b%2)
             res=(res*a)%c;  //res=mul_mod(res,a,c);
         a=(a*a)%c;   //a=mul_mod(a,a,c);

例题二的代码中用的注释中的格式,在快速乘的基础上执行快速幂,更快,有的题不需要(如题一),而有的题则必须这样用(如题二,不调快速乘A不了),建议直接按注释格式打板子吧,谁嫌快呢

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值