pow

How to power the number without using the "pow" function?
std::exp(exponent * std::log(base))
can you explain how to use it?
You use it instead of std::pow(base, exponent).
or you multiply the number in a loop as long as the exponent tells
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.
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;
}
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.
sorry, but i really can't understand what are you say --" please explain it in different way, easy way :(
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
Topic archived. No new replies allowed.