Friday, 7 July 2017

Java Code to generate the sequence where each member is the sum of adjacent factorials.

Problem:

Generate the sequence where each member is the sum of adjacent factorials, i.e

f3 = 1! + 0!
f4 = 2! + 1!
f5 = 3! + 2!

Solution:
package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SequencePrint2 {

List<Integer> numbers = new ArrayList<Integer>();

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
SequencePrint2 sequencePrint2 = new SequencePrint2();
sequencePrint2.generateTheSequence(n);
sequencePrint2.printTheResult();
s.close();
}

public void generateTheSequence(int n){
for(int i = 0; i<n; i++){
numbers.add(findFactorial(i) + findFactorial(i+1));
}
}

public int findFactorial(int number){
int product = 1;
for(int i = 1; i <=number; i++){
product = product * i;
}
return product;
}

public void printTheResult(){
System.out.println(numbers);
}

}



Output:

enter the n value
10
[2, 3, 8, 30, 144, 840, 5760, 45360, 403200, 3991680]


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...