# Tribonacci Numbers in C++

C++Server Side ProgrammingProgramming

Here we will see how to generate the Tribonacci numbers using C++. The Tribonacci numbers are similar to the Fibonacci numbers, but here we are generating a term by adding three previous terms. Suppose we want to generate T(n), then the formula will be like below −

T(n) = T(n - 1) + T(n - 2) + T(n - 3)

The first few numbers to start, are {0, 1, 1}

## Algorithm

tribonacci(n):
Begin
first := 0, second := 1, third := 1
print first, second, third
for i in range n – 3, do
next := first + second + third
print next
first := second
second := third
third := next
done
End

## Example

Live Demo

#include<iostream>
using namespace std;
long tribonacci_gen(int n){
//function to generate n tetranacci numbers
int first = 0, second = 1, third = 1;
cout << first << " " << second << " " << third << " ";
for(int i = 0; i < n - 3; i++){
int next = first + second + third;
cout << next << " ";
first = second;
second = third;
third = next;
}
}
main(){
tribonacci_gen(15);
}

## Output

0 1 1 2 4 7 13 24 44 81 149 274 504 927 1705