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