針對澤肯多夫定理的 C++ 程式?
此處我們將看到如何判斷給定和是否是透過對某些不相鄰的斐波那契數進行加法而得出的,若答案為肯定,這些數分別是什麼?例如,若給出和為 10,則其由 8 和 2 相加得出。8 和 2 均為斐波那契數,而且它們不相鄰。我們來看看這個演算法,以便了解這個想法。
演算法
nonNeighbourFibo(sum)
Begin while sum > 0, do fibo := greatest Fibonacci term but not greater than sum print fibo sum := sum - fibo done End
示例
#include<iostream>
using namespace std;
int fibonacci(int n) {
if (n == 0 || n == 1)
return n;
// get the greatest Fibonacci Number smaller than n.
int prev = 0, curr = 1, next = 1;
while (next <= n) {
prev = curr;
curr = next;
next = prev + curr;
}
return curr;
}
void nonNeighbourFibo(int sum) {
while (sum > 0) {
int fibo = fibonacci(sum);
cout << fibo << " ";
sum = sum - fibo;
}
}
int main() {
int sum = 120;
cout << "Sum is same as Non-adjacent Fibonacci terms: ";
nonNeighbourFibo(sum);
}輸出
Sum is same as Non-adjacent Fibonacci terms: 89 21 8 2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP