问题:求n的m次方。
解法:正常求的话,时间复杂度是O(N).快速幂的时间复杂度是O(log2(N)).
若n为偶数,n^m=n^(m/2)*n^(m/2);
若n为奇数, n^m=n*(n^(m/2)*n^(m/2));
递归算法:
#include <iostream>
using namespace std;
typedef long long ll;
int quick_pow(ll a,ll b)
{
if(b<=1)
{
return a;
}
ll res=quick_pow(a,b>>1);
res*=res;
if (b&1) //n为奇数
res *= a;
return res;
}
int main()
{
ll n,m;
while(cin>>n>>m)
{
cout<<quick_pow(n,m);
}
return 0;
}
非递归算法:
#include <iostream>
typedef long long ll;
using namespace std;
int quick_pow(ll a,ll b)
{
ll res=1;
while(b>0)
{
if(b&1)
{
res=res*a;
}
a*=a;
b>>=1;
}
return res;
}
int main()
{
ll n,m;
while(cin>>n>>m)
{
cout<<quick_pow(n,m);
}
return 0;
}