C++ 中的第 N 个 Tribonacci 数
假设我们有一个值 n,我们必须生成第 n 个三阶斐波纳契数。三阶斐波纳契数与斐波纳契数类似,但我们通过添加前三个数来生成一个数。假设我们要生成 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
示例 (C++)
#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); }
输入
15
输出
15th Tribonacci Term: 1705
广告