Số Tetranacci là tổng của bốn số trước đó.
T(n) = T(n-1) + T(n-2) + T(n-3) + T(n-4)
Bốn số khởi tạo: {0, 1, 1, 2}.
Thuật toán
tetranacci(n):
Bắt đầu
first := 0, second := 1, third := 1, fourth := 2
in first, second, third, fourth
cho i từ 0 đến n-4, làm
next := first + second + third + fourth
in next
first := second
second := third
third := fourth
fourth := next
kết thúc
Kết thúc
Ví dụ mã C++
#include<iostream>
using namespace std;
long tetranacci_gen(int n){
int first = 0, second = 1, third = 1, fourth = 2;
cout << first << " " << second << " " << third << " " << fourth << " ";
for(int i = 0; i < n - 4; i++){
int next = first + second + third + fourth;
cout << next << " ";
first = second;
second = third;
third = fourth;
fourth = next;
}
}
int main(){
tetranacci_gen(15);
}
Kết quả đầu ra
0 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872