C++ Program for Zeckendorf's Theorem?

C++Server Side ProgrammingProgramming

Here we will see how to check whether the given sum is found by adding some nonneighbouring Fibonacci numbers or not, if so, what are the numbers? For example if the give sum value is 10, this is sum of 8 and 2. Both 8 and 2 are Fibonacci terms and they are not adjacent. Let us see the algorithm to get the idea.

Algorithm

nonNeighbourFibo(sum)

Begin
   while sum > 0, do
      fibo := greatest Fibonacci term but not greater than sum
      print fibo
      sum := sum - fibo
   done
End

Example

#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);
}

Output

Sum is same as Non-adjacent Fibonacci terms: 89 21 8 2
raja
Published on 31-Jul-2019 16:10:35
Advertisements