C++ 中的 Tribonacci 數
本文我們將瞭解如何利用 C++ 生成 Tribonacci 數。Tribonacci 數類似於 Fibonacci 數,但此處的項是透過加三個前一項生成的。假設我們要生成 T(n),則公式如下 −
T(n) = T(n - 1) + T(n - 2) + T(n - 3)
以開始的幾個數字為 {0, 1, 1}
演算法
tribonacci(n): Begin first := 0, second := 1, third := 1 print first, second, third for i in range n – 3, do next := first + second + third print next first := second second := third third := next done End
示例
#include<iostream>
using namespace std;
long tribonacci_gen(int n){
//function to generate n tetranacci numbers
int first = 0, second = 1, third = 1;
cout << first << " " << second << " " << third << " ";
for(int i = 0; i < n - 3; i++){
int next = first + second + third;
cout << next << " ";
first = second;
second = third;
third = next;
}
}
main(){
tribonacci_gen(15);
}輸出
0 1 1 2 4 7 13 24 44 81 149 274 504 927 1705
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP