Google interview question

Write a program to find (x^y) % z

Interview Answers

Anonymous

19 Feb 2011

I guess the point is how to avoid overflow. Good algorithms for this does not lead to overflow and return the correct answer; normal ones may easily lead to overflow.

1

Anonymous

15 Jun 2012

I guess we need to use Congruences from Number theory here

Anonymous

13 Jan 2011

I think there is some point we need to check. first will x be negative? If so, we need to handle this problem In addition, in the case y is very large, a O(y) algorithm is not a good idea, we might need to use the O(lg Y) one.

Anonymous

12 Jan 2011

result = x mod z for i = 2 to y do result = (result * x) mod z

Anonymous

7 Feb 2011

(x ^ y) % z is equal to: (x << (y-1)) % z