class PowerRec
{
static double powRec(double x, int power)
{
if (power == 1){
return x;
}
return x * powRec(x, power - 1);
}
public static void main(String args[])
{
double x = 2;
System.out.println (x + " to the fourth is " + powRec (x, 4));
}
}
Asked
Active
Viewed 160 times
0

user unknown
- 35,537
- 11
- 75
- 121

sctts-lol
- 557
- 5
- 9
-
1It doesn't. However `x * (x ^ (n - 1)) == x ^ n` – Elliott Frisch Feb 08 '18 at 00:56
-
Doing some code layout revealed a marouding line. Fixed it. – user unknown Feb 18 '18 at 15:24
2 Answers
1
you have two returning statement in a row in your code. And wrong powRec method
static double powRec(double x, int power) {
if (power == 0) {
return 1;
}
return x * powRec(x, power - 1);
}

loljeene
- 79
- 1
- 6
-
Yeah, I made a mistake, but I still don't understand how 'powRec(x, power-1) ' works? – sctts-lol Feb 08 '18 at 01:22
-
You use recursion method call. Method powRec(x,4) call powRec(x,3), then powRec(x,2)... Until power==0. You can read https://en.wikipedia.org/wiki/Recursion_(computer_science) – loljeene Feb 08 '18 at 01:34
0
a³ = a * a ² = a * (a * a)
This is, what the code essentially does.
Now your new homework: Replace (x * y) with a call to mul (x, y), and solve the problem of multiplication with addition in the same habit.

user unknown
- 35,537
- 11
- 75
- 121