Wednesday, 5 July 2017

Java Code to generate the sequence 0 1 1 2 4 7 .....

Problem:

Given a = 0, b=1, c=1 are the first three numbers of some sequence. All other numbers in the sequence are generated from the sum of their three three most recent predecessors. Design an algorithm to generate the sequence.


Solution:

package com.myprograms;

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

public class SequencePrint {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(0);
numbers.add(1);
numbers.add(1);
for(int i = 3; i<n; i++){
numbers.add(i, numbers.get(i-3) + numbers.get(i-2) + numbers.get(i-1));
}
System.out.println(numbers);
s.close();
}

}


Output:

enter the n value
10
[0, 1, 1, 2, 4, 7, 13, 24, 44, 81]


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...