算法学习之快速幂

来源:互联网 发布:转炉煤气 优化控制 编辑:程序博客网 时间:2024/06/06 11:40

一.算法分析

由分治算法计算幂函数,由递归式T(n)=T(n/2)+(-)(1)计算可知算法复杂度为O(lgn),比普通的算法O(n)快了许多。

二.代码实现

#include <iostream>#include <cstring>using namespace std;long long pow2(int x,int n){long long temp;if(n==0) return 1;else if(n==1) return x;else if(n%2==0){temp=pow2(x,n/2);return temp*temp;}else {temp=pow2(x,(n-1)/2);return temp*temp*x;}}int main(){while(1){int x,n;cin>>x>>n;cout<<pow2(x,n)<<endl;}return 0;}


 

0 0
原创粉丝点击