public int logpower(int x,int m)
{
//Calculates x^m in O(log m) time
if(m==1)
return x;
else if(m%2!=0)
return logpower(x,m/2)*logpower(x,m/2)*x;
else
return logpower(x,m/2)*logpower(x,m/2);
}
Subscribe to:
Post Comments (Atom)
Design and implementation of interesting data structures and algorithms. You may find it useful either in your computer science course curriculum or in technical interviews of companies like Microsoft, Amazon, Google, Yahoo, Sun, Oracle etc
1 comment:
Hi,
This algorithm takes more than log m times because the number of recursive invocations are doubled everytime.
i.e for logpower(2,8) - it will call logpower(2,4) - 2 times
logpower(2,2) - 4 times
logpower(2,1) - 8 times
Actually for log m complexity, the recursive call should be made only once. i.e instead of
logpower(x,m/2) * logpower(x,m/2)..it should be
int power = logpower(x,m/2);
int result = power * power //even no
Post a Comment