Programming language is JAVA: Write a public static method named static long tri
ID: 3840900 • Letter: P
Question
Programming language is JAVA:
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
TribonacciNumGen.java
import java.util.Scanner;
public class TribonacciNumGen {
public static void main(String[] args) {
// Scanner class object is used to read the inputs entered by the user
Scanner s = new Scanner(System.in);
// getting the index value entered by the user
System.out.print("Enter the value of Index : ");
int n = s.nextInt();
long res = tribonacci(n, 0, 1, 1);
// Displaying the Tribonacci Series for the number
System.out.print("The Triibonocci Number for the index " + n + " is :"
+ res);
}
/*
* This tribonacci() method will calculate nth tribonocci number
* and return to the caller
* Params: number of type integer Return :
* tribonocci number of type Long
*/
public static int tribonacci(int n, int a, int b, int c) {
int l = 0;
if (n == 1)
return a;
if (n == 2)
return b;
if (n == 3)
return c;
else {
for (int i = 1; i < n - 2; i++) {
l = a + b + c;
a = b;
b = c;
c = l;
}
return l;
}
}
}
__________________
Output:
Enter the value of Index : 10
The Triibonocci Number for the index 10 is :81
___________________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.