Engaged Employer

## Interview Question

Senior Software Engineer Interview Palo Alto, CA

# Write some pseudo code to raise a number to a power.

0

pretty trivial...

Interview Candidate on Jul 18, 2010
3

int raise(num, power){
if(power==0) return 1;
if(power==1) return num;
return(raise(num, power-1)*num);
}

vittal on Jul 25, 2010
3

double Power(int x, int y)
{
double ret = 1;
double power = x;

while (y > 0)
{
if (y & 1)
{
ret *= power;
}
power *= power;
y >>= 1;
}

return ret;
}

Anonymous on Aug 29, 2010
1

In Ruby:
def power(base, power)
product = 1
power.times do
product *= base
end
product
end

puts "2^10 = 1024 = #{power(2,10)}"
puts "2^0 = 1 = #{power(2,0)}"
puts "2^1 = 2 = #{power(2,1)}"

Ted Behling on Sep 6, 2010
2

If I were an interviewer, I would ask the Aug 29, 2010 poster why he used bitwise operators, and whether he would deploy that code in a production environment, or if he merely wanted to demonstrate, for purposes of the interview, that he understands bitwise operations.

Ted Behling on Sep 6, 2010
0

Because it uses dynamic programming and is lots more efficient than your algorithm.

Dah on Oct 12, 2010
0

If the power is not integer, use ln and Taylor series

Evgeni on Dec 6, 2010
1

If I'm the interviewer, none of above answers is acceptable.
What if y < 0? what if y < 0 and x == 0?
I'm seeing an endless recursion that will eventually overflow the stack, and the none-recursive one just simply returns 1.

Jerry on Feb 10, 2011
0

There is a way to do this in a logN way rather than N.

function power(x, n)
{
if n == 1
return x;

// Even numbers
else if (n%2 == 0)
return square( power (x, n/2));

// Odd numbers
else
return power(x, n-1);

}

This is from Programming pearls.. interesting way.

deveffort on Feb 18, 2011
5

small mistake

function power(x, n)
{
if n == 1
return x;

// Even numbers
else if (n%2 == 0)
return square( power (x, n/2));

// Odd numbers
else
return power(x, n-1) * x;

}

deveffort on Feb 18, 2011