Exponential function without using pow() in C++

I am trying to write a program that solves exponents without using the pow () function. I think I need to use a loop to generate how many times the base multiplies itself as long as the exponent is positive. Any ideas?


One approach to this problem:

int power(int n,int e)
{
double T = 1;
for(int k=1; k<=e; k++)
T = T*n;
return T;
}
Time Complexity of above program is O(N)

Recursive Approach

int power(int n,int e)
{
    if(e==0) return 1;
    if(e%2==0)
   {
       return power(n,e/2,"if") * power(n,e/2,"if");
   }
   else {
      return n*power(n,e-1, "else") ;
   }
}

Comments

Popular posts from this blog

Ace the Amazon Interview

Map in c++

Google Interview Preparation