I have a problem with my homework and i need help please!
Question 1:
Complete the Java methods below so that raiseToPower(x,n) will raise the number x to an integer power n (that is, to calculate the value xn ). Remember that x-n = 1/xn, and that x0 = 1.
You should do this in the fewest number of steps possible (that is, in O(log n) time).
Give a solution which is non-recursive (iterative):
This is my solution :
public static double raiseToPower (double x, int n) {
double res=1;
boolean neg=false;
if(n<0)
{
neg=true;
}
if(n>0)
for (int i=0;i<n;i++) {
res = res * x;
}
if(neg==true) {
n=n*-1;
for (int i=0;i<n;i++) {
res = res * x;
}
res=1/res;
}
return res;
}
but this is not correct because is not efficiency
This my error for example: 52.49 to the power of 9 solved in 9 steps, but it could have been done in 4 steps 89.89 to the power of 75 solved in 75 steps, but it could have been done in 7 steps 78.57 to the power of 63 solved in 63 steps, but it could have been done in 6 steps 70.17 to the power of 44 solved in 44 steps, but it could have been done in 6 steps
Note:must not be used in method java.lang.MathPow
Question 2:
I need write code exactly like Question 1 but in recursive
This is my Question: Give a recursive solution:
This is my code:
public static double raiseToPower (double x, int n) {
ouble dev=0.0;
if (n == 0) {
return 1;
} else {
if (n < 0) {
double count= raiseToPower (x, n+1);
dev=count*x;
return 1 / raiseToPower (x, -n);
}
if (n > 0) {
double count= raiseToPower (x, n-1);
dev=count*x;
}
}
return dev;
}
This code is correct but not efficiency.
This is my error for example:
53.31 to the power of 44 solved in 44 steps, but it could have been done in 6 steps 6.90 to the power of 74 solved in 74 steps, but it could have been done in 7 steps 80.76 to the power of 76 solved in 76 steps, but it could have been done in 7 steps 51.44 to the power of 86 solved in 86 steps, but it could have been done in 7 steps 76.26 to the power of 50 solved in 50 steps, but it could have been done in 6 steps 63.53 to the power of 93 solved in 93 steps, but it could have been done in 7 steps
Note:must not be used in method java.lang.MathPow
Thank you everyone for helping and solving both problems !!!