Search code examples
javaseriesfactorial

Write a program in Java to solve the series


The series:

S=1+(3/2)!+(5/3)!+(7/4)!…n.

n is taken as input from user.

This is the code i used:

import java.util.Scanner;

public class Series_4b {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        double a = 1.0, i = 2.0, n = in.nextInt();
        double s = a;
        while ((a/i) < n) {
            a = a + 2;
            i = i + 1;
            s += factorial(a / i);
        }
        System.out.println(s);
    }

    static double factorial(double a) {
        double factorial = 1;
        for (int i = 1; i <= a; i++) {
            factorial *= i;
        }
        return factorial;
    }
}

This does not work.

Note: This is my school project so I can use only BlueJ IDE.


Solution

  • You can use this :

    import java.util.Scanner;
    public class Series { 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number: ");
        int n = sc.nextInt();
        double sum = 1.0;
        int num = 1;
        for(int i = 2; i <= n; i++) { 
            num = num + 2;
            double factorial = 1.0;
            for(int j = 1; j <= num; j++) {
                factorial = factorial * j;
            }
            sum = sum + (num / factorial);
        }
        System.out.println("The sum of the series is: " + sum);
    }
    }