Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading