I have to write a static method to compute x^n for an integer n,
WITHOUT using Math.pow(). they gave these formulas: when n < 0, x^n
is 1/x^-n (although, shouldn't it be 1/x^n?), n>0 and even, x^n = (x^
(n/2)^2), n>0 and odd, x^n = x^(n-1) * x.
anyhow..my problem is these error messages:
MyMath.java:46: operator ^ cannot be applied to double,double
answer = 1.0/(x^(-n));
^
C:\Documents and Settings\Chris\My Documents\MyMath.java:52:
operator ^ cannot be applied to double,double
answer = (x^(n/2))^2;
^
C:\Documents and Settings\Chris\My Documents\MyMath.java:56:
operator ^ cannot be applied to double,double
answer = (x^(n-1)) * x;
^
Here is my method:
public static double intPower(double x, double n)
{
if(n<0)
answer = 1.0/(x^(-n));
else if(n>0)
{
if(n%2 == 0) // if n is even
{
answer = (x^(n/2))^2;
}
else // n must be odd
{
answer = (x^(n-1)) * x;
}
}
return answer;
}
The method name and parameter variables are given. answer is a
static instance variable.