Javatpoint Logo
Javatpoint Logo

Tetranacci Number in Java

In this section, we will learn what is a Tetranacci number and also create Java programs to check if the given number is a Tetranacci number or not. The Tetranacci number program is frequently asked in Java coding interviews and academics.

Tetranacci Number

Tetranacci numbers are similar to the Fibonacci numbers. The only difference is that the Fibonacci number is dependent on the last two Fibonacci numbers, whereas a Tetranacci number is dependent on the last four Tetranacci numbers.

Mathematically, the Tetranacci numbers are represented as:

T(0) = 0,

T(1) = 1,

T(2) = 1,

T(3) = 2,

T(n) = T(n - 4) + T(n - 3) + T(n - 2) + T(n - 1), where n >= 4

Thus,

T(4) = T(0) + T(1) + T(2) + T(3) = 0 + 1 + 1 + 2 = 4

T(5) = T(1) + T(2) + T(3) + T(4) = 1 + 1 + 2 + 4 = 8

T(6) = T(2) + T(3) + T(4) + T(5) = 1 + 2 + 4 + 8 = 15

T(7) = T(3) + T(4) + T(5) + T(6) = 2 + 4 + 8 + 15 = 29

T(8) = T(4) + T(5) + T(6) + T(7) = 2 + 4 + 8 + 15 + 29 = 56

Java Program for Tetranacci Numbers: Iterative Approach

The following program generates the Tetranacci numbers using the mathematical formula defined above.

FileName: TetranacciNumberIterative.java

Output:

The first 20 Tetranacci numbers are: 
0 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 39648 76424

Java Program for Tetranacci Numbers: Recursive Approach

If we treat the value of the first four Tetranacci numbers as the base case, then the above mentioned mathematically formula turns out to be the recursive formula too to find the other Tetranacci numbers. The following code uses the above mathematical formula to generate the next Tetranacci number recursively.

FileName: TetranacciNumberRecursive.java

Output:

The first 20 Tetranacci numbers are: 
0 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 39648 76424






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA