C++ 中的泰特拉奇數
在此,我們將看到如何使用 C++ 生成泰特拉奇數。泰特拉奇數類似於斐波那契數,但我們在這裡透過新增四個前項來生成一項。假設我們想生成 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP