# N-th Tribonacci Number in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we have a value n, we have to generate n-th Tribonacci number. 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}

We can solve them by following this algorithm −

## Algorithm

• first := 0, second := 1, third := 1
• for i in range n – 3, do
o next := first + second + third
o first := second, second := third, third := next
• return third

## Example (C++)

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;
for(int i = 0; i < n - 3; i++){
int next = first + second + third;
first = second;
second = third;
third = next;
}
return third;
}
main(){
cout << "15th Tribonacci Term: " << tribonacci_gen(15);
}

## Input

15

## Output

15th Tribonacci Term: 1705
Updated on 28-Apr-2020 11:07:03