pow

Sep 26, 2012 at 8:55am
How to power the number without using the "pow" function?
Sep 26, 2012 at 9:05am
std::exp(exponent * std::log(base))
Sep 26, 2012 at 9:10am
can you explain how to use it?
Sep 26, 2012 at 9:18am
You use it instead of std::pow(base, exponent).
Sep 26, 2012 at 9:24am
or you multiply the number in a loop as long as the exponent tells
Sep 26, 2012 at 11:03am
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.
Sep 26, 2012 at 1:14pm
or you multiply the number in a loop as long as the exponent tells


1
2
3
4
5
int answer = 1;
for (int i=0; i < power; i++)
{
   answer *= number;
}
Sep 26, 2012 at 3:09pm
When the power is a whole number, then repeated multiplication

When the power p is a whole number all you need is log2p multiplications - see http://en.wikipedia.org/wiki/Exponentiation_by_squaring - no logarithms involved.
Oct 9, 2012 at 2:37pm
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
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
Topic archived. No new replies allowed.