JAVA 00293: answer is: static long fibFast(int n, long a, long b){ if(n==0) retu
ID: 3841716 • Letter: J
Question
JAVA
00293: answer is: static long fibFast(int n, long a, long b){
if(n==0)
return a;
else
return fibFast(n-1,b,a+b);
}
Write a public static method named static long tribonacci(int n, long a, long b, long c)
that returns the nth "tribonacci number" when initialially called with tribonacci(n, 0, 1, 1).
Tribonacci numbers start with 0, 1, 1, for tribonacci(0), tribonacci(1), tribonacci(2).
Then each subsequent number is the sum or the previous three numbers.
That means the first ten elements in the sequence are 0, 1, 1, 2, 4, 7, 13, 24, 44, 81.
Use an algorithm similar to Exercise 00293.
At every iteration , a, b and c will be the values of three consecutive tribonacci numbers (assuming the initial call is tribonacci(n, 0, 1, 1).
As n goes down by 1, b takes the position of a, c take the position of b and a+b+c takes the position of c.
When n = 0, the return value will be a.
Explanation / Answer
import java.util.*;
class TestTribonacci
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the value of n : ");
int n = scan.nextInt(); //input n
long result = tribonacci(n, 0, 1, 1);
System.out.println("Tribonacci Number at "+n+ " = "+result);
}
static long tribonacci(int n, long a, long b, long c)
{
if (n == 1)
return a;
else if (n == 2)
return b;
else if(n==3)
return c;
else
return tribonacci(n-1,a,b,c)+tribonacci(n-2,a,b,c)+tribonacci(n-3,a,b,c);//recursive calls
}
}
Output:
Enter the value of n : 10
Tribonacci Number at 10 = 81
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.