เราจะมาดูวิธีการสร้างตัวเลขเตตรานาชชีโดยใช้ C++ ตัวเลข Tetranacci นั้นคล้ายกับตัวเลข Fibonacci แต่ในที่นี้ เรากำลังสร้างคำศัพท์โดยการเพิ่มคำศัพท์ก่อนหน้าสี่คำ สมมติว่าเราต้องการสร้าง T(n) จากนั้นสูตรจะเป็นดังนี้ -
T(n) = T(n - 1) + T(n - 2) + T(n - 3) + T(n - 4)
ตัวเลขสองสามตัวแรกที่จะเริ่มต้นคือ {0, 1, 1, 2}
อัลกอริทึม
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
ตัวอย่าง
#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);
} ผลลัพธ์
0 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872