You are currently viewing Methods to get the Sum of the First nth Time period of a Sequence in Java

Methods to get the Sum of the First nth Time period of a Sequence in Java


The problem

Your process is to write down a operate that returns the sum of the next collection as much as nth time period(parameter).

Sequence: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

Guidelines:

  • It’s essential to spherical the reply to 2 decimal locations and return it as String.
  • If the given worth is 0 then it ought to return 0.00
  • You’ll solely be given Pure Numbers as arguments.

Examples: (Enter –> Output)

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

The answer in Java code

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

Choice 2:

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

Choice 3:

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

Take a look at circumstances to validate our resolution

import static org.junit.Assert.*;
import java.util.*;
import org.junit.Take a look at;

public class NthSeriesTest {
	@Take a look at
	public void test1() {
		assertEquals("1.57", NthSeries.seriesSum(5));
	}
	@Take a look at
	public void test2() {
		assertEquals("1.77", NthSeries.seriesSum(9));
	}
	@Take a look at
	public void test3() {
		assertEquals("1.94", NthSeries.seriesSum(15));
	}
}

Leave a Reply