总结--快速幂

来源:互联网 发布:网络段子里的老司机 编辑:程序博客网 时间:2024/06/05 15:46

快速幂取余的思想是:

当 b为偶数时

(a^b mod m)=(a^(b/2) mod m)*(a^(b/2) mod m);

当b为奇数时 a^b=a^(b/2)*a^(b/2)*a^1;

(a^b mod m)=(a^b mod m)=(a^(b/2) mod m)*(a^(b/2) mod m)*(a mod m);

这种求幂的时间复杂度是O(log2n);

以下为实现代码:

#include<iostream>using namespace std;const long long int mod=10e8+7;                  //mod 根据需要赋值long long power(long long base,long long index){long long temp;                               if(index==0) return 1;                    base%=mod;temp=power(base,index/2);                 //递归求base^(index/2)的值temp=(temp*temp)%mod;if(index & 1==1) return (temp*base)%mod;  //指数的奇偶讨论return temp;}int main(){int base,index;long long res;cin>>base>>index;res=power(base,index);cout<<res<<endl;return 0;}



原创粉丝点击