Above function can be optimized to O(logn) by calculating power(x, y/2) only once and storing it.
int
power(
int
x, unsigned
int
y)
{
int
temp;
if
( y == 0)
return
1;
temp = power(x, y/2);
if
(y%2 == 0)
return
temp*temp;
else
return
x*temp*temp;
}
Let us extend the pow function to work for negative y and float x.
From http://www.programcreek.com/2012/12/leetcode-powx-n/
public double power(double x, int n) { if (n == 0) return 1; double v = power(x, n / 2); if (n % 2 == 0) { return v * v; } else { return v * v * x; } } public double pow(double x, int n) { if (n < 0) { return 1 / power(x, -n); } else { return power(x, n); } }
float
power(
float
x,
int
y)
{
float
temp;
if
( y == 0)
return
1;
temp = power(x, y/2);
if
(y%2 == 0)
return
temp*temp;
else
{
if
(y > 0)
return
x*temp*temp;
else
return
(temp*temp)/x;
}
}
Also refer to http://www.programcreek.com/2012/12/leetcode-powx-n/
Read full article from Write a C program to calculate pow(x,n) | GeeksforGeeks
No comments:
Post a Comment