
可用递归实现,也可用非递归实现。
方法一(递归实现):
#include<iostream>
using namespace std ;
int Pow( int n , int m ) {
if( m == 0 )
return 1 ;
if( m == 1 )
return n ;
double P = Pow( n , m >> 1 ) ;
P *= P ;
if( m % 2 )
P *= n ;
return P ;
}
int main() {
int n , m ;
cin >> n >> m ;
cout << Pow( n , m ) << endl ;
return 0 ;
}
方法二(非递归实现):#include<iostream>
using namespace std ;
int Pow( int a , int b ) {
int t = 1 ;
while(b != 0 ) {
if( b % 2 == 1 )
t *= a ;
b /= 2 ;
a *= a ;
}
return t ;
}
int main() {
int n , m ;
cin >> n >> m ;
cout << Pow( n , m ) << endl ;
return 0 ;
}