Pair of fibonacci numbers with a given sum and minimum absolute difference

Given an integer N(less than 10^6), the task is to find a pair of Fibonacci numbers whose sum is equal to the given N and the absolute difference between the chosen pair is minimum.
Print -1 if there is no solution.

Examples:

Input: N = 199
Output: 55 144
Explanation
199 can be represented as sum 55 and 144 which has the minimum difference.

Input: N = 1830
Output: 233 1597
Explanation
1830 can be represented as sum 233 and 1597 which has the minimum difference.

Approach: The idea is to use hashing to precompute and store the Fibonacci nodes up to the maximum value to make checking easy and efficient (in O(1) time).



After precomputing the hash:

  1. Start a loop from (N / 2) to 1 (to minimize the absolute difference) and check whether the loop counter ‘i’ and ‘N – i’ are both Fibonacci.
  2. If they are Fibonacci, then we will print them and break out of the loop.
  3. If the number N cannot be represented as the sum of two Fibonacci numbers, then we will print -1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the pair of
// Fibonacci numbers with a given sum
// and minimum absolute difference
  
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000005
  
// Hash to store all the
// Fibonacci numbers
set<int> fib;
  
// Function to generate fibonacci Series
// and create hash table
// to check Fibonacci numbers
void fibonacci()
{
    // Adding the first two Fibonacci
    // numbers into the Hash set
    int prev = 0, curr = 1, len = 2;
    fib.insert(prev);
    fib.insert(curr);
  
    // Computing the remaining Fibonacci
    // numbers based on the previous
    // two numbers
    while (len <= MAX) {
        int temp = curr + prev;
        fib.insert(temp);
        prev = curr;
        curr = temp;
        len++;
    }
}
  
// Function to find the pair of
// Fibonacci numbers with the given
// sum and minimum absolute difference
void findFibonacci(int N)
{
  
    // Start from N/2 such that the
    // difference between i and
    // N - i will be minimum
    for (int i = N / 2; i > 1; i--) {
  
        // If both 'i' and 'sum - i' are
        // fibonacci numbers then print
        // them and break the loop
        if (fib.find(i) != fib.end()
            && fib.find(N - i) != fib.end()) {
  
            cout << i << " " << (N - i) << endl;
            return;
        }
    }
  
    // If there is no Fibonacci pair
    // possible
    cout << "-1" << endl;
}
  
// Driver code
int main()
{
    // Generate the Fibonacci numbers
    fibonacci();
  
    int sum = 199;
  
    // Find the Fibonacci pair
    findFibonacci(sum);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the pair of
// Fibonacci numbers with a given sum
// and minimum absolute difference
import java.util.*;
   
class GFG{
    // Hash to store all the
    // Fibonacci numbers
    static int MAX=1000005;
    static  Set<Integer> fib=new HashSet<Integer>();
      
    // Function to generate fibonacci Series
    // and create hash table
    // to check Fibonacci numbers
    static void fibonacci()
    {
        // Adding the first two Fibonacci
        // numbers into the Hash set
        int prev = 0, curr = 1, len = 2;
        fib.add(prev);
        fib.add(curr);
      
        // Computing the remaining Fibonacci
        // numbers based on the previous
        // two numbers
        while (len <= MAX) {
            int temp = curr + prev;
            fib.add(temp);
            prev = curr;
            curr = temp;
            len++;
        }
    }
      
    // Function to find the pair of
    // Fibonacci numbers with the given
    // sum and minimum absolute difference
    static void findFibonacci(int N)
    {
      
        // Start from N/2 such that the
        // difference between i and
        // N - i will be minimum
        for (int i = N / 2; i > 1; i--) {
      
            // If both 'i' and 'sum - i' are
            // fibonacci numbers then print
            // them and break the loop
            if (fib.contains(i)  && fib.contains(N - i)) {
      
                System.out.println(i+" "+(N - i));
                return;
            }
        }
      
        // If there is no Fibonacci pair
        // possible
        System.out.println("-1");
    }
      
    // Driver code
    public static void main(String args[])
    {
        // Generate the Fibonacci numbers
        fibonacci();
      
        int sum = 199;
      
        // Find the Fibonacci pair
        findFibonacci(sum);
      
          
    }
}
  
  
// This code is contributed by AbhiThakur

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the pair of
// Fibonacci numbers with a given sum
// and minimum absolute difference
using System;
using System.Collections.Generic;
  
class GFG{
    // Hash to store all the
    // Fibonacci numbers
    static int MAX=100005;
    static  HashSet<int> fib=new HashSet<int>();
       
    // Function to generate fibonacci Series
    // and create hash table
    // to check Fibonacci numbers
    static void fibonacci()
    {
        // Adding the first two Fibonacci
        // numbers into the Hash set
        int prev = 0, curr = 1, len = 2;
        fib.Add(prev);
        fib.Add(curr);
       
        // Computing the remaining Fibonacci
        // numbers based on the previous
        // two numbers
        while (len <= MAX) {
            int temp = curr + prev;
            fib.Add(temp);
            prev = curr;
            curr = temp;
            len++;
        }
    }
       
    // Function to find the pair of
    // Fibonacci numbers with the given
    // sum and minimum absolute difference
    static void findFibonacci(int N)
    {
       
        // Start from N/2 such that the
        // difference between i and
        // N - i will be minimum
        for (int i = N / 2; i > 1; i--) {
       
            // If both 'i' and 'sum - i' are
            // fibonacci numbers then print
            // them and break the loop
            if (fib.Contains(i)  && fib.Contains(N - i)) {
       
                Console.WriteLine(i+" "+(N - i));
                return;
            }
        }
       
        // If there is no Fibonacci pair
        // possible
        Console.WriteLine("-1");
    }
       
    // Driver code
    public static void Main(String []args)
    {
        // Generate the Fibonacci numbers
        fibonacci();
       
        int sum = 199;
       
        // Find the Fibonacci pair
        findFibonacci(sum);
    }
}
  
// This code is contributed by sapnasingh4991

chevron_right


Output:

55 144

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.