📜  特里波纳契词

📅  最后修改于: 2022-05-13 01:57:06.572000             🧑  作者: Mango

特里波纳契词

就像斐波那契字一样,一个 Tribonacci 字。是一个特定的数字序列。 Tribonacci 词是通过重复连接形成的,就像斐波那契词是通过重复加法形成的一样。但与斐波那契词不同的是,Tribonacci 词是通过重复添加最后三个术语而形成的,并且它的前三个术语彼此不同。

In Tribonacci word,
  S(0) = 1, 
  S(1) = 12, 
  S(2) = 1213,
  S(3) = 1213121 
  ..... 
where S(n) = S(n-1) + S(n-2) + S(n-3) and + 
represents the concatenation of 
strings. 

任务是为给定的数字 n 找到第 n 个 Tribonacci 字。
例子:

Input : n = 4
Output : S(4) = 1213121121312

Input : n = 3
Output : S(3) = 1213121

就像在斐波那契词的程序中一样,我们在这里使用寻找第 n 个斐波那契词的迭代概念来寻找第 n 个 Tribonacci 词,我们可以使用迭代概念。因此,为了找到第 n 个 Tribonacci 词,我们将采用三个字符串Sn_1、Sn_2 和 Sn_3,它们分别代表 S(n-1)、S(n-2) 和 S(n-3),并且在每次迭代中,我们将更新 tmp = Sn_3, Sn_3 = Sn_3 + Sn_2 + Sn_1, Sn_1 = Sn_2 和 Sn_2 = tmp 这样我们可以找到第 n 个 tribonacci 字。

C++
// C++ program for nth Fibonacci word
#include 
using namespace std;
 
// Returns n-th Tribonacci word
string tribWord(int n) {
  string Sn_1 = "1";
  string Sn_2 = "12";
  string Sn_3 = "1213";
  string tmp;
  for (int i = 3; i <= n; i++) {
    tmp = Sn_3;
    Sn_3 += (Sn_2 + Sn_1);
    Sn_1 = Sn_2;
    Sn_2 = tmp;
  }
 
  return Sn_3;
}
 
// driver program
int main() {
  int n = 6;
  cout << tribWord(n);
  return 0;
}


Java
// program for nth Tribonacci word
class GFG {
 
// Returns n-th Tribonacci word
static String tribWord(int n) {
    String Sn_1 = "1";
    String Sn_2 = "12";
    String Sn_3 = "1213";
    String tmp;
    for (int i = 3; i <= n; i++) {
    tmp = Sn_3;
    Sn_3 += (Sn_2 + Sn_1);
    Sn_1 = Sn_2;
    Sn_2 = tmp;
    }
 
    return Sn_3;
}
 
// Driver code
public static void main(String[] args) {
    int n = 6;
    System.out.print(tribWord(n));
}
}
// This code is contributed by Anant Agarwal.


Python3
# Python3 Program for nth
# Tribonacci word
 
# Returns n-th Tribonacci word
def tribWord(n):
    Sn_1 = "1"
    Sn_2 = "12"
    Sn_3 = "1213"
    for i in range(3, n+1):
        tmp = Sn_3
        Sn_3 += (Sn_2 + Sn_1)
        Sn_1 = Sn_2
        Sn_2 = tmp
 
    return Sn_3
 
# Driver code
n = 6
print(tribWord(n))
 
# This code is contributed By Anant Agarwal.


C#
// C# program for nth Tribonacci word
using System;
 
class GFG {
 
    // Returns n-th Tribonacci word
    static string tribWord(int n)
    {
        string Sn_1 = "1";
        string Sn_2 = "12";
        string Sn_3 = "1213";
        string tmp;
         
        for (int i = 3; i <= n; i++) {
            tmp = Sn_3;
            Sn_3 += (Sn_2 + Sn_1);
            Sn_1 = Sn_2;
            Sn_2 = tmp;
        }
     
        return Sn_3;
    }
     
    // Driver code
    public static void Main() {
         
        int n = 6;
         
        Console.WriteLine(tribWord(n));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

12131211213121213121121312131211213121213121

https://youtu.be/TM5

-ET2AKJY