## The challenge

Your task is to write a function that returns the sum of the following series up to nth term(parameter).

 ``````1 `````` ``````Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... ``````

Rules:

• You need to round the answer to 2 decimal places and return it as String.
• If the given value is 0 then it should return 0.00
• You will only be given Natural Numbers as arguments.

Examples: (Input –> Output)

 ``````1 2 3 `````` ``````1 --> 1 --> "1.00" 2 --> 1 + 1/4 --> "1.25" 5 --> 1 + 1/4 + 1/7 + 1/10 + 1/13 --> "1.57" ``````

## The solution in Java code

Option 1:

 ``````1 2 3 4 5 6 7 8 `````` ``````public class NthSeries { public static String seriesSum(int n) { double sum = 0.0; for (int i = 0; i < n; i++) sum += 1.0 / (1 + 3 * i); return String.format("%.2f", sum); } } ``````

Option 2:

 ``````1 2 3 4 5 6 `````` ``````import java.util.stream.IntStream; public class NthSeries { public static String seriesSum(int n) { return String.format("%.2f", IntStream.range(0, n).mapToDouble(x -> 1.0 / (3 * x + 1)).sum()); } } ``````

Option 3:

 `````` 1 2 3 4 5 6 7 8 9 10 11 `````` ``````import java.util.*; public class NthSeries { public static String seriesSum(int n) { double sum=0.0; while(n>0){ sum+=1.0/(3*n-2); n--; } return String.format("%.2f",sum ).toString(); } } ``````

## Test cases to validate our solution

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 `````` ``````import static org.junit.Assert.*; import java.util.*; import org.junit.Test; public class NthSeriesTest { @Test public void test1() { assertEquals("1.57", NthSeries.seriesSum(5)); } @Test public void test2() { assertEquals("1.77", NthSeries.seriesSum(9)); } @Test public void test3() { assertEquals("1.94", NthSeries.seriesSum(15)); } } ``````