Tribonacci Word in C++


The Tribonacci Word is a sequence of digits. This is similar to the Fibonacci Words. Tribonacci Word is constructed by repeated concatenation of three previous strings

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

The first few strings to start, are {1, 12, 1213} So the next one will be 1213 + 12 + 1 = 1213121

Algorithm

tribonacci_word(n):
Begin
   first := 1, second := 12, third := 1213
   print first, second, third
   for i in range 3 to n, do
      temp := third
      third := third + second + first
      print third
      first := second
      second := next
   done
End

Example

 Live Demo

#include<iostream>
using namespace std;
long tribonacci_word_gen(int n){
   //function to generate n tetranacci words
   string first = "1";
   string second = "12";
   string third = "1213";
   cout << first << "\n" << second << "\n" << third << "\n";
   string tmp;
   for (int i = 3; i <= n; i++) {
      tmp = third;
      third += (second + first);
      cout << third <<endl;
      first = second;
      second = tmp;
   }
}
main(){
   tribonacci_word_gen(6);
}

Output

1
12
1213
1213121
1213121121312
121312112131212131211213
12131211213121213121121312131211213121213121

Updated on: 25-Sep-2019

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements