In: Computer Science
(TestSumSeries.java) Write a recursive method that sums up the
following series:
s(i) = 1/1+ 3/3+3/5+5/7+⋯+ (i+1)/(2i+1)+(i+2)/(2i+1) i = 0, 1, 2, 3, … When i is even, the term is (i+1)/(2i+1) When i is odd, the term is (i+2)/(2i+1) In the main method, display the s(i) for i = 0, 1, 2, 3, 4, 5
Code Segment:
import java.io.*;
public class TestSumSeries{
// Recursive method to compute sum of the series
public static double series_sum(int i)
{
// if i becomes negative stop adding, return 0
if(i<0)
return 0;
// if i is non-negative, do the computation
else
{
// if i is even
if(i%2==0)
{
// add the term corresponding to even i
return((double)(i+1)/(2*i+1) + series_sum(i-1));
}
// if i is odd
else
{ // add the term corresponding to odd i
return((double)(i+2)/(2*i+1) + series_sum(i-1));
}
}
}
public static void main(String[] args) {
double result;
// loop from 0 to 5
for(int i=0; i<=5;i++)
{
// calling the series_sum method for every i from 0 to 5
result = series_sum(i);
// printing the result
System.out.println("s(" + i + ") = " + result);
System.out.println();
}
}
}
Output: