Computer Science, asked by Varun1870, 1 year ago

Java program to print the sum of the following series:
p=x^2/2+x^3/4+x^4/6......x^n/n+2

Answers

Answered by muvvadhanush007
2
This is a mathematical series program where a user must enter the number of terms up to which the sum of the series is to be found. Following this, we also need the value of x, which forms the base of the series.
Examples:

Input : x = 9, n = 10 Output : -5.1463 Input : x = 5, n = 15 Output : 0.2837

Recommended: Please try your approach on {IDE}first, before moving on to the solution.

Simple approach : 
We use two nested loops to compute factorial and use power function to compute power.

C

Java

// Java program to get the sum of the series

import java.io.*;

  

class MathSeries {

  

    // Function to get the series

    static double Series(double x, int n)

    {

        double sum = 1, term = 1, fct, j, y = 2, m;

  

       // Sum of n-1 terms starting from 2nd term

        int i;

        for (i = 1; i < n; i++) {

            fct = 1;

            for (j = 1; j <= y; j++) {

                fct = fct * j;

            }

            term = term * (-1);

            m = Math.pow(x, y) / fct;

            m = m * term;

            sum = sum + m;

            y += 2;

        }

        return sum;

    }

  

    // Driver Code

    public static void main(String[] args)

    {

        double x = 3;

        int n = 4;

        System.out.println(Math.round(Series(x, n) * 

                                10000.0) / 10000.0);

    }

}


Ben193: please follow me
Similar questions