用C++的方法:用 long long就够用
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int m,n;
while(scanf("%d%d",&m,&n)!=EOF){
long long s=1;
for(int i=0;i<n;i++){
s=s*m;
}
cout<<s<<endl;
}
return 0;
}
用C的方法:要考虑到大数的问题
递归算法:
int pow(int x,int n)
{
if(n==1)
return x;
else
if(n & 1)
return x*pow(x,n/2);
else
return pow(x,n/2);
}
int pow(int x,int n)
{
if(n==1)
return x;
else
if(n & 1)
return x*pow(x,n/2);
else
return pow(x,n/2);
}
非递归算法:
int pow(int x,int n)
{
int temp(x),res(1);
while(n)
{
if(n & 1)
{
res*=temp;
}
temp*=temp;
n>>1;
}
return res;
}
也可用快速幂算法:
a的b次方为例:
例如
![](https://i-blog.csdnimg.cn/blog_migrate/7a151bc9fd5f896f95d86dab9542d49c.png)
11的二进制是1011
11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1
因此,我们将a¹¹转化为算
![](https://i-blog.csdnimg.cn/blog_migrate/637d4eace7e3771314d7af39477bb6d3.png)
程序代码:
int pow4( int x,int y)
{
int result;
if( n=0 )
return 1;
else
{
while( ( n & 1 )==0)
{
n>>1;
x*=x;
}
}
return x;
n>>1;
while( n!= 0 )
{
x*=x;
if( ( n & 1 )!=0 )
result*=x;
n>>1;
}
return result;
}