Interview Question

Software Engineer II Interview Chicago, IL

How can you solve n^m efficiently only using +, -, *, /.

Tags:
algorithm
Answer

Interview Answer

4 Answers

0

This is one solution that doesn't deal with negative exponents
exp(n, m) {
  if (m == 0) return 1
  if (m == 1) return n
  exp = exp(n, m / 2)
  if ( isOdd(m) )
    exp = exp * n
  return exp
}

Interview Candidate on Dec 11, 2010
0

int f(int n, int m)
{
   if(m==0) return 1;
   if(m==1) return n;
   n=n*f(n,(m-1));
   return n;
}

ritvik on Feb 4, 2011
2

There is no need to solve it recursively.
it is pretty simple
int calculateExp(int n, int m) {
     exp = n
     for (i = 1; i <= m; i++) {
           exp = exp*n
     }
     return exp;
}

Dhruv on Oct 18, 2011
2

Disadvantage of recursion is the large amount of space on the stack for a large m in this case.

Dhruv on Oct 18, 2011

Add Answers or Comments

To comment on this, Sign In or Sign Up.