针对泽肯多夫定理的 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