double pow2(double x, int n)
{
if (n < 0)
{
x = 1/x;
n = -n;
}
double base = x;
double result = 1;
while(n)
{
if (n&1)
{
result *= base;
}
base = base*base;
n >>= 1;
}
return result;
}
double pow(double x, int n)
{
if(n == 0) return 1;
if(n == 1) return x;
bool negative = false;
if(n < 0)
{
negative = true;
n = -n;
}
double r = pow(x, n/2);
r = r*r;
if ( n%2 != 0) r *= x;
if (negative) r = 1/r;
return r;
}
#include <stdio.h>
int main(int argc, char** argv)
{
double base = 7.21;
for (int i = 0; i < 21; ++i)
{
printf("%f, %d, pow = %28.7f, pow2 = %28.7f\n", base, i,
pow(base, i),
pow2(base, i));
}
return 0;
}