Problem:
Design an algorithm to find the sum of the first n terms of the series
fn = 0! + 1! + 2! + 3! + 4! .....+ n!
Solution:
package com.myprograms;
import java.util.Scanner;
public class SumOfNFactorials {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter n value");
int n = s.nextInt();
SumOfNFactorials sumOfNFactorials = new SumOfNFactorials();
System.out.println("the sum is: " + sumOfNFactorials.findFactorialSum(n));;
s.close();
}
public int findFactorial(int n){
int product = 1;
for(int i=1; i<= n; i++){
product = product * i;
}
return product;
}
public int findFactorialSum(int n){
int sum = 0;
for(int i = 0; i<= n; i++){
sum = sum + findFactorial(i);
}
return sum;
}
}
Output:
enter n value
4
the sum is: 34
Design an algorithm to find the sum of the first n terms of the series
fn = 0! + 1! + 2! + 3! + 4! .....+ n!
Solution:
package com.myprograms;
import java.util.Scanner;
public class SumOfNFactorials {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter n value");
int n = s.nextInt();
SumOfNFactorials sumOfNFactorials = new SumOfNFactorials();
System.out.println("the sum is: " + sumOfNFactorials.findFactorialSum(n));;
s.close();
}
public int findFactorial(int n){
int product = 1;
for(int i=1; i<= n; i++){
product = product * i;
}
return product;
}
public int findFactorialSum(int n){
int sum = 0;
for(int i = 0; i<= n; i++){
sum = sum + findFactorial(i);
}
return sum;
}
}
Output:
enter n value
4
the sum is: 34
enter n value
10
the sum is: 4037914
No comments:
Post a Comment