Open In App

Java Program for Zeckendorf\’s Theorem (Non-Neighbouring Fibonacci Representation)

Improve
Improve
Like Article
Like
Save
Share
Report

Given a number, find a representation of number as sum of non-consecutive Fibonacci numbers.

Examples:

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.

The idea is to use Greedy Algorithm.

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 




// Java program for Zeckendorf's theorem. It finds representation
// of n as sum of non-neighbouring Fibonacci Numbers.
class GFG {
    public static 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
    public static 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
            System.out.print(f + " ");
  
            // Reduce n
            n = n - f;
        }
    }
  
    // Driver method to test
    public static void main(String[] args)
    {
        int n = 30;
        System.out.println("Non-neighbouring Fibonacci Representation of " + n + " is");
  
        printFibRepresntation(n);
    }
}


Output:

Non-neighbouring Fibonacci Representation of 30 is
21 8 1

Please refer complete article on Zeckendorf’s Theorem (Non-Neighbouring Fibonacci Representation) for more details!



Last Updated : 06 Dec, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads