Ở đây chúng ta sẽ xem cách tạo các số Tetranacci bằng C ++. Các số Tetranacci tương tự như các số Fibonacci, nhưng ở đây chúng ta đang tạo một số hạng bằng cách thêm bốn số hạng trước đó. Giả sử chúng ta muốn tạo T (n), thì công thức sẽ như sau -
T(n) = T(n - 1) + T(n - 2) + T(n - 3) + T(n - 4)
Một vài số đầu tiên để bắt đầu, là {0, 1, 1, 2}
Thuật toán
tetranacci(n): Begin first := 0, second := 1, third := 1, fourth := 2 print first, second, third, fourth for i in range n – 4, do next := first + second + third + fourth print next first := second second := third third := fourth fourth := next done End
Ví dụ
#include<iostream>
using namespace std;
long tetranacci_gen(int n){
//function to generate n tetranacci numbers
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;
}
}
main(){
tetranacci_gen(15);
} Đầu ra
0 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872