Currently, my best effort has resulted in complexity O(log[n]^2):
int power(x,n)
{
int mult=1, temp=x, i=1, j=1;
while (n>1)
{
mult=mult*x;
x=temp;
for (i=1;i<=log[n];i++)
{
x=x*x;
j=j*2;
}
n=n-j;
i=1;
j=1;
}
if (n==1)
return (mult*temp);
return (mult);
}
P.S Thank you funkymushroom for helping me with my bad English :)
The idea behind implementing this operation in logarithmic time is to use the following (mathematical) equivalences (here n/2 denotes integer division):
This can easily be implemented recursively according to:
An implementation such as this will yield a O[log(n)] complexity since the input (the variable n) is halved in each step of the recursion.
What you need is to use repeated squaring. Check this out