假设我们有一个值n,我们必须生成第n个Tribonacci数。Tribonacci数与Fibonacci数相似,但是在这里我们通过添加三个前项生成一个项。假设我们要生成T(n),则公式将如下所示-
T(n) = T(n - 1) + T(n - 2) + T(n - 3)
开始的前几个数字是{0,1,1}
我们可以通过遵循以下算法来解决它们-
• 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
#include<iostream> using namespace std; long tribonacci_gen(int n){ //函数生成n个正弦编号 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); }
15
输出结果
15th Tribonacci Term: 1705