📜  Zeckendorf定理的C ++程序(非邻近斐波那契表示法)

📅  最后修改于: 2021-05-31 23:51:42             🧑  作者: Mango

给定一个数字,找到作为非连续斐波纳契数之和的数字表示形式。

例子:

Input:  n = 10
Output: 8 2
8 and 2 are two non-consecutive Fibonacci Numbers
and sum of them is 10.

Input:  n = 30
Output: 21 8 1
21, 8 and 1 are non-consecutive Fibonacci Numbers
and sum of them is 30.

这个想法是使用贪婪算法。

1) Let n be input number

2) While n >= 0
     a) Find the greatest Fibonacci Number smaller than n.
        Let this number be 'f'.  Print 'f'
     b) n = n - f 
// C++ program for Zeckendorf's theorem. It finds representation
// of n as sum of non-neighbouring Fibonacci Numbers.
#include 
using namespace std;
  
// Returns the greatest Fibonacci Numberr smaller than
// or equal to n.
int nearestSmallerEqFib(int n)
{
    // Corner cases
    if (n == 0 || n == 1)
        return n;
  
    // Find the greatest Fibonacci Number smaller
    // than n.
    int f1 = 0, f2 = 1, f3 = 1;
    while (f3 <= n) {
        f1 = f2;
        f2 = f3;
        f3 = f1 + f2;
    }
    return f2;
}
  
// Prints Fibonacci Representation of n using
// greedy algorithm
void printFibRepresntation(int n)
{
    while (n > 0) {
        // Find the greates Fibonacci Number smaller
        // than or equal to n
        int f = nearestSmallerEqFib(n);
  
        // Print the found fibonacci number
        cout << f << " ";
  
        // Reduce n
        n = n - f;
    }
}
  
// Driver method to test
int main()
{
    int n = 30;
    cout << "Non-neighbouring Fibonacci Representation of "
         << n << " is \n";
    printFibRepresntation(n);
    return 0;
}
输出:
Non-neighbouring Fibonacci Representation of 30 is 
21 8 1

请参阅有关Zeckendorf定理(非邻域斐波那契表示法)的完整文章,以了解更多详细信息!

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”