快速幂

快速幂;

可以解决的问题:毫无疑问一定是数值很大,且和幂数有关的数学题;

优点:暴力增长,减少循环次数,提高速率;

解决一:2^20问题

解决二: 2^20%5问题

解决一:幂乘积问题

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int main()
{
//    int a,b;
    long long ans=1,a,b;//注意暴力速度增长,需要用unsigned int 或Long long int ;
    cout<<"please input the a and b:"<<endl;
    cin>>a>>b;
    while(b!=0)
    {
        if(b&1!=0)//b%2!=0;指b是奇数;
        {
            ans*=a;
        }
        a*=a;
        b/=2;
    }
    cout<<ans<<endl;
    return 0;
}
那么是如何处理的尼??

根据二进制的增长特点,对指数进行增长;1 2 4 8 16 32 64   (1*1 2*2 4*4 16*16 这种增长趋势)即:a=a*a;//底的乘积效果

我们解释一下,x&1==0偶;x&1!=0奇;

a^11=a^(2^0)+a^(2^1)+a^(2^3);

解决二:取模问题;

#include<iostream>
#include<string>
using namespace std;
int main()
{
    int a,b,c,ans=1;
   cout<<"input the a b and c:"<<endl;
   while(cin>>a>>b>>c)
   {//a:底,b:指数 ,c:模值;(如2^20%5)a=2,b=20,c=5;
    ans=1;
    while(b!=0)
   {
         if(b%2!=0)//这里是奇数的地盘
         {
             cout<<"ans:"<<ans<<endl;
             ans=ans*a%c;//不难发现只是在结果幂乘积的结果之上加了一个取模c而已
         }
        b/=2;
        a=a*a%c;
   }
    cout<<ans<<endl;
   }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值