1.00e+00f
INF
1.00e+00f
2.49e+00f
5.00e-01f
思路:使用快速幂求幂次。但是指数可能为负数。因此负数转换成整数的相反数。然后特判,考虑底数为0,且指数小于0(错误情况);处理的情况还有指数为0(前面已经处理到了);
版本一:书上(就是快速幂,只不过用递归实现,和快速幂时间效率相等)
/* ***********************************************
Author :bo-jwolf
Created Time :2015年02月09日 星期一 12:49:32
File Name :1514.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define Abs 1e-8
double PowerWithUnsignedExponent( double base, unsigned int exponent ){
if( exponent == 0 )
return 1;
if( exponent == 1 )
return base;
double result = PowerWithUnsignedExponent( base, exponent >> 1 );
result *= result;
if( exponent & 0x1 == 1 )
result *= base;
return result;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int Case;
double base;
int exponent;
while( scanf( "%d", &Case ) != EOF ){
while( Case-- ){
scanf( "%lf%d", &base, &exponent );
bool flag = true;
if( fabs(base) <= Abs && exponent < 0 )
flag = false;
if( flag ){
bool pos = true;
if( exponent < 0 ){
exponent = - exponent;
pos = false;
}
double res = PowerWithUnsignedExponent( base, exponent );
if( pos )
printf( "%.2ef\n", res );
else
printf( "%.2ef\n", 1.0/res );
}
else
puts( "INF" );
}
}
return 0;
}
版本二:
/* ***********************************************
Author :bo-jwolf
Created Time :2015年02月09日 星期一 13:36:23
File Name :1514a.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define Abs 1e-10
double PowerWithUnsignedExponent( double base, unsigned int exponent ){
double res = 1.0;
while( exponent ){
if( exponent & 1 ){
exponent--;
res *= base;
}
exponent >>= 1;
base *= base;
}
return res;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int Case;
double base;
int exponent;
while( scanf( "%d", &Case ) != EOF ){
while( Case-- ){
scanf( "%lf%d", &base, &exponent );
int flag = true;
if( fabs( base ) <= Abs && exponent < 0 )
flag = false;
if( flag ){
int pos = true;
if( exponent < 0 ){
pos = false;
exponent = -exponent;
}
double res = PowerWithUnsignedExponent( base, exponent );
if( pos )
printf( "%.2ef\n", res );
else
printf( "%.2ef\n", 1.0 / res );
}
else
puts( "INF" );
}
}
return 0;
}