#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
long double Pow(const long double x, const int power)
{ // x ^ 0 is 1
if (power == 0)
return 1;
// x ^ 1 is x
if (power == 1)
return x;
int c, i, k;
long double res;
long double px;
// We observe that x ^ power could be written as a product of
// factors, in which we may find: x ^ 1, x ^ 2, x ^ 4, x ^ 8 ...
// A factor appears in the product if in the binary representation
// of "power", the corresponding digit is 1. The result is multiplied
// with "power", only if the digit is 1. E.g: x ^ 13 = x ^ 8 + x ^ 4 + x ^ 1,
// because 13 in binary is 1101.
// To convert the power to binary, we must divide it with 2 at every iteration.
for (i = 1, px = x, res = 1, k = power; k; k /= 2)
{ c = k % 2; // Obtain the digit
// Check if the digit is 1. Only if it is 1 then we
// multiply res with px
if (c)
res *= px;
px *= px;
}
return res;
}
int main()
{ // Recommended, because Pow may return a big number.
std::cout << std::setprecision(10);
// This is here to demonstrate the ability of the function:
time_t start = clock();
std::cout << "<cmath> pow() took: ";
for (unsigned long long int i = 0; i < 999999999; i++)
double x = pow(300.0f, 4);
time_t stop = clock();
// <cmath> pow takes between 1950 - 2100 ticks for me.
std::cout << stop - start << " ticks!n";
start = clock();
std::cout << "My pow() took: ";
for (unsigned long long int i = 0; i < 999999999; i++)
double x = Pow(300.0f, 4);
stop = clock();
// The above Pow takes between 1000 - 1150 ticks for me.
std::cout << stop - start << " ticks!n";
std::cin.get();
return 0;
}