Google interview question

Implement a fast exponentiation function

Interview Answers

Anonymous

23 Mar 2011

double recExp(b,p){ if(p==1) return b; double t=recExp(b,int(p/2)); return t*t*((p%2)?b:1); }

1

Anonymous

26 Jan 2012

def expo(a, n): result = 1 while (n != 0): if n % 2 == 1: result *= a a *= a n /= 2 return result This is a binary version. In calculating a to the b, it's easy to convert the number b into binary representation. It's also Log(N)

Anonymous

3 Feb 2011

divide and conquer ?

Anonymous

3 Feb 2011

long fast_pow_n(int x, int n) { int temp_pow; if(n/2>=1) { (int) tem_pow=n/2; sub_result=fast_pow_n(x,temp_pow); temp_result=sub_result*sub_result; if(n%2==1) temp_result*=x; return temp_result; } else { return x; } }