eg:
n=10,10%2==0,
10/2=5, 5%2==1,4*
5/2==2, 2%2==0,4*256
0/2=0, 1024
递归算法
#include<iostream>
using namespace std;
long long quick_pow(int b,int e)
{
if(b==0)
return 0;
if(e==0)
return 1;
if(e%2==0)
{
int temp=quick_pow(b,e/2);
return temp*temp;
}
if(e%2!=0)
return b*quick_pow(b,e-1);
}
int main()
{
long long base,exponet;//底数,指数
cin>>base>>exponet;
cout<<quick_pow(base,exponet);
return 0;
}
非递归算法
#include<iostream>
using namespace std;
long long quick_pow(int base,int exponent)
{
long long result=1;
while(exponent>0)
{
if(exponent%2!=0)
result*=base;
base*=base;
exponent/=2;
}
return result;
}
int main()
{
long long base,exponent;
cin>>base>>exponent;
cout<<quick_pow(base,exponent);
return 0;
}