I need to write a recursive method to compute the following series:
m(i) = 1/3 + 2/5 + 3/7 + 4/9 + 5/11 + 6/13 + .... + i/(2i + 1)
Then I need to write a program that displays m(i)
for i = 1,2,....10
.
I understand the basic idea of recursion I had done 2 programs so far, one for factorials and one for a Fibonacci number sequence. This problem has me stumped.
This is what I have so far.
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(m(i));
}
}
public static double m(int i) {
if (i == 1)
return 1;
else
return ???;
}
First, it looks like your base case is off - that should be 1/3 (the first number in the series).
For your else, you should return the next step down added to the current step. Given your series, the current step is i/(2i + 1)
.
public static double m(int i) {
if (i == 1) {
// Base case is 1 - return the first number in the series
return 1/3;
} else {
// Get the current step (ie the current iteration of m(i))
double curStep = i / (2.0 * i + 1.0);
// Return the current step plus the next step down
return curStep + m(i - 1);
}
}