Generalized Tribonacci Sequence-JAVA CODING Description The tribonacci sequence
ID: 3689396 • Letter: G
Question
Generalized Tribonacci Sequence-JAVA CODING
Description
The tribonacci sequence is a generalization of the fibonacci sequence, where the nth term in the sequence is given by the following recurrence relation
T(n)=T(n1)+T(n2)+T(n3)T(n)=T(n1)+T(n2)+T(n3)
Specification
Create a class GeneralTribonacci. At a minimum, your class should have the following methods:
* genTrib that takes four numbers: the first three numbers in the sequence, as well as an index n . This should return the nth term in the given sequence.
If the first three numbers are given in non-ascending order, or if the index given is less than 0, this should throw a (runtime) SequenceStartException
NOTE The indexing should start from 0, so the first term in the sequence is the 0th term
* A main method, that asks the user to input the beginning of the tribonacci sequence as well as an index nn , then prints the nthnth term in the sequence.
Example Dialog
Note
You should experiment with the running time of your algorithm, in terms of the index.
E.g. how fast can it find the 10th term? How about the 40th ?
Experiment further to see if you can find a faster algorithm with the same result.
Submit both GeneralTribonacci and SequenceStartException
Explanation / Answer
GeneralTribonacci.java
import java.io.*;
import java.util.Scanner;
public class GeneralTribonacci {
public static void main(String[] args)
{
try{
Scanner in=new Scanner(new InputStreamReader(System.in));
System.out.println("Enter the first three terms to start:");
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
if(a != 0 || b != 1 || c != 1){
throw new SequenceStartException("Non asecending order Exception ");
}
System.out.println("Enter the index of the term to find:");
int n=in.nextInt();
int d=a+b+c;
System.out.print(a+" "+b+" "+c);
for(int i=3;i<=n;i++)
{
System.out.print(" "+d);
a=b;
b=c;
c=d;
d=a+b+c;
}
}
catch(SequenceStartException e){
System.out.println(e);
}
}
}
SequenceStartException.java
public class SequenceStartException extends Exception {
String str1;
public SequenceStartException(String s){
this.str1 = s;
}
public String toString(){
return (str1) ;
}
}
Output:
Enter the first three terms to start:
0 1 1
Enter the index of the term to find:
5
0 1 1 2 4 7
Enter the first three terms to start:
0 -1 1
Non asecending order Exception
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.