Sep 26, 2012 at 8:55am UTC
How to power the number without using the "pow" function?
Sep 26, 2012 at 9:05am UTC
std::exp(exponent * std::log(base))
Sep 26, 2012 at 9:10am UTC
can you explain how to use it?
Sep 26, 2012 at 9:18am UTC
You use it instead of std::pow(base, exponent)
.
Sep 26, 2012 at 9:24am UTC
or you multiply the number in a loop as long as the exponent tells
Sep 26, 2012 at 11:03am UTC
When the power is a whole number, then repeated multiplication (or division, for negative values) would work. (Or for negative values, use repeated multiplication and take the reciprocal at the end).
But if the number of repetitions is very large, this would be inefficient. In that case, you could use the log , antilog method suggested above.
Oct 9, 2012 at 2:37pm UTC
sorry, but i really can't understand what are you say --" please explain it in different way, easy way :(
Oct 9, 2012 at 3:47pm UTC
This function will work for integer exponents (base can be any type that you like).
1 2 3 4 5
int MyPow(int base, int exp)
{
if (exp) return base * MyPow(base,exp-1);
return 1;
}
Edit: Actually, I like that idea of Exponentiation by squaring:
1 2 3 4 5 6 7 8
template <typename T>
T MyPow(T base, int exp)
{
if (n == 0) return 1;
if (n < 0) return 1. / MyPow(base,-1*exp);
if (n%2) return base * MyPow( MyPow(base,(exp-1)/2) ,2);
return MyPow( MyPow(base,exp/2) ,2);
}
Last edited on Oct 9, 2012 at 4:53pm UTC