Skip to content

How to get the Sum of the First nth Term of a Series in Java

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 +...
Code language: HTTP (http)

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"
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

public class NthSeries { public static String seriesSum(int n) { double sum = 0.0; for (int i = ; i < n; i++) sum += 1.0 / (1 + 3 * i); return String.format("%.2f", sum); } }
Code language: Java (java)

Option 2:

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

Option 3:

import java.util.*; public class NthSeries { public static String seriesSum(int n) { double sum=0.0; while(n>){ sum+=1.0/(3*n-2); n--; } return String.format("%.2f",sum ).toString(); } }
Code language: Java (java)

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)); } }
Code language: Java (java)

See also  How to Create a Secret in Kubernetes
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x