Reputation: 31
Here is my assignment:
Write a program that contains a recursive method to compute the following:
m(i) = 1/2 + 2/3 +...i/i+1
The main method should display:
____________________
| i m(i) |
| |
| 1 ------ 0.5 |
| |
| 2 ------ 1.1667 |
| |
| ...... |
| |
| 19 ------ 16.4023|
| |
| 20 ------ 17.3546|
|____________________|
Here is what I have so far. I'm fairly new to programming and having some trouble understanding recursive methods. Any advice is appreciated. Thanks!
public class RecursionMethod
{
public static void main (String[] args)
{
System.out.println("i\tm(i)\n--------------");
for (int i = 1; i <= 20; i++)
{
System.out.println(m(i));
}
}
public static double m(int x)
{
if (x==1)
return .5;
else
return m(x/x+1);
}
}
Upvotes: 2
Views: 84
Reputation: 1330
This should work..give it a try...
public class RecursionMethod
{
public static void main (String[] args)
{
System.out.println("i\tm(i)\n--------------");
for (int i = 1; i <= 20; i++)
{
System.out.println(i +"---+---"+m(i));
}
}
public static double m(int x)
{
if (x==1)
return .5;
else if (x==0)
return 0;
else
return ((double)x/(double)(x+1)+m(x-1));
}
}
Where you went wrong was here return m(x/x+1);
With this statement you basically created a stack explosion...
With recursion your aim should be reaching the base condition ie
if(i==1)
statement..The only way to reach this is by decrementing the value of i until you reach i==1 and thus rewinding the stack from there.
Hope this Helps
Nice try Evan
Upvotes: 2
Reputation: 393781
The idea is to add the current element of the series to the rest of the series (which you get from the recursive call) :
public static double m(int x)
{
if (x==1)
return .5;
else
return (double)x/(x+1) + m(x-1);
}
Note that the casting to double is important, since without it you'll be doing int division, which will return 0.
Upvotes: 3
Reputation: 3267
This is what you were looking for: The recursive part here is to get the value for a particular value for i, and then recursively call for i-1.
public static double resursiveSum(int x) {
if (x == 1) {
return .5;
} else {
return ((double)x / (double)(x + 1)) + resursiveSum(x - 1);
}
}
Upvotes: 3