The challenge

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

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 --> 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:

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:

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:

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

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));
	}
}