1.

Write An O(log2(n)) Algorithm To Find X^n?

Answer»

INT computeXn(int X, int N)
{
if(n == 2)
{
RETURN x*x;
}
ELSE if(n % 2 == 0)
{
int y = computeXn(x, n/2);
return y*y;
}
else if(n % 2 == 1)
{
int y = computeXn(x, n/2);
return y*y*x;
}
}

 

int computeXn(int x, int n)
{
if(n == 2)
{
return x*x;
}
else if(n % 2 == 0)
{
int y = computeXn(x, n/2);
return y*y;
}
else if(n % 2 == 1)
{
int y = computeXn(x, n/2);
return y*y*x;
}
}

 



Discussion

No Comment Found