首页 > 代码库 > 快速幂
快速幂
#include <iostream>
using namespace std;
int f( int a, int b ) //二分求幂(一般)
{
int r = 1, base = a;
while( b != 0 )
{ if( b % 2 )
r *= base;
base *= base;
b /= 2;
}
return r;
}
int main(int argc, char *argv[])
{
int a,n;
while(cin>>a>>n)
cout<<f(a,n)<<endl;
return 0;
}
#include <iostream>
using namespace std;
int f( int a, int b ) //快速求幂(位操作)
{
int r = 1, base = a;
while( b != 0 )
{ if( b & 1 )
r *= base;
base *= base;
b >>= 1;
}
return r;
}
int main(int argc, char *argv[])
{
int a,n;
while(cin>>a>>n)
cout<<f(a,n)<<endl;
return 0;
}
#include <iostream>
using namespace std;
int f( int a, int n )
{
if(n==0) return 1;
if(n%2==1) return a*f(a,n/2)*f(a,n/2);
else return f(a,n/2)*f(a,n/2);
}
int main(int argc, char *argv[])
{
int a,n;
while(cin>>a>>n)
cout<<f(a,n)<<endl;
return 0;
}
#include <iostream>
using namespace std;
int f( int a, int n )
{
int t ;
if(n==0) return 1;
t=f(a,n/2);
if(n%2==1) return a*t*t;
else return t*t;
}
int main(int argc, char *argv[])
{
int a,n;
while(cin>>a>>n)
cout<<f(a,n)<<endl;
return 0;
}