Google Interview Question

write a function to calculate X^N

Interview Answers

Anonymous

Jul 10, 2010

int pow (int x, int n) { if (n == 0) return 1; if (n == 1) return x; if (n & 0x1) // n odd return pow(x*x, n/2) * x; else // n even return pow(x*x, n/2); } Runtime: O(log n)

9

Anonymous

Jan 18, 2011

public static long pow(int x, int y) { if(y == 0 || x == 1) return 1; if(y == 1) return x; int pow = 1; long result = x; while((pow<<1) <= y) { result *= result; pow = pow<<1; } return result * (pow == y ? 1 : pow(x,y - pow)); } Almost the same solution like that from mackerzed.

Anonymous

Jul 20, 2010

i think you need the array way to solve it .. you all are going beyond bounds of an int

Anonymous

Jul 6, 2010

int pow(int x, int n){ return x*1<

Anonymous

Jul 6, 2010

^^ does not work: int pwr(int x, int n){ int c = x; while(--n) x *= c; return x; }