减治法求指数

#include <iostream>
#include <cmath>
using namespace std;

//************************************
// Method: 减治法求指数
// FullName: TreatmentCompulate
// Access: public
// Returns: int
// Qualifier: a>1 n>0
// Parameter: int a
// Parameter: int n
//************************************
int TreatmentCompulate(int a,int n)
{
if (n <= 0)
{
return 1;
}

int nextN = n/2;
int nextValue = TreatmentCompulate(a,nextN);

if (n%2 == 0)
{
return nextValue*nextValue;
}
else
{
return nextValue*nextValue*a;
}
}

int main()
{
int a = 5;
int n=10;

cout<<a<<"("<<n<<") = "<<TreatmentCompulate(a,n);

cout<<endl;

int result = 1;
for (int i=0;i<n;++i)
{
result *= a;
}

cout<<"result: "<<result;

return 0;
}

image
原文地址:https://www.cnblogs.com/sharpfeng/p/2673712.html