Reputation: 117
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 ???;
}
Upvotes: 0
Views: 5682
Reputation: 29
Does it need to be recursive? if not, a simple for loop will do the trick.
double sum = 0;
for(int x = 0; x < i; x++)
{
sum += x / (2.0 * x + 1);
}
return sum;
If it must be recursive, you need to start by properly identifying the base case. In this situation, your base case could be either 0 or 1. Examples:
Base case is 0:
public static double m(int i)
{
if(i==0)
return 0;
else
{
double sum = i/(2.0 * i + 1);
return sum + m(i-1);
}
}
Base case is 1:
public static double m(int i)
{
if(i==1)
return 1.0/3.0;
else
{
double sum = i/(2.0 * i + 1);
return sum + m(i-1);
}
}
Upvotes: 0
Reputation: 12243
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);
}
}
Upvotes: 3