Interview question:
Calculate x ^ y in O(log n)
There are different answers like “Use the Indian Power algorithm” or
double power(double x, int y)
{
if(y == 0) return 1;
double d = power(x, y/2);
if(y%2 == 0) return d*d;
else return x*d*d;
}
-
is it a correct answer?
-
is there any better way of writing a code for this question?
This is called Exponentiation by Squaring. As far as implementation goes, it is a matter of taste. Your recursive implementation is good, but non-recursive implementations (from the link above) may look a little cleaner to people who do not like recursion or erroneously believe that it is somehow “wasteful” or “slow”.