Calculate the sum of the series based on a given number in Java

The series: 1×2 + 2×3×4 + … + n×(n + 1)× … ×2n

For example, if you enter 3, the output should be 386, because (1×2)+(2×3×4)+(3×4×5×6)=386.

I’ve tried various loops, but that is not even close to the desired result.

Though, I’ll post it here:

int sum = 0, n = sc.nextInt();
for (int i = 1; i <= n; i++) {
    sum = sum + i * (i + 1); 
}

>Solution :

I do not intent to resolve it for you, but you are missing that multiplication itself needs another loop for each of the number in the loop you created (from n to 2n).

I am giving you the solution, but hope you will try to understand it to realize where you missed it.

public class MyClass {
private static long calculateSeries(int n){
    long sum=0;
    for (int i = 1; i <= n; i++) {

    // You are missing multiplication part in your logic.

        long mres=1;
        for (int j=i; j <= 2*i; j++){
            mres=mres*j;
        }
    sum = sum + mres; 
    }
    return sum;
 }

public static void main(String args[]) {
  System.out.println(calculateSeries(3));
}
}

Leave a Reply