Largest subset whose all elements are Fibonacci numbers - GeeksforGeeks

22 Mar, 2022
Given an array with positive number the task is that we find largest subset from array that contain elements which are Fibonacci numbers.Asked in Facebook Examples :  
Input : arr[] = {1, 4, 3, 9, 10, 13, 7};
Output : subset[] = {1, 3, 13}
The output three numbers are Fibonacci
numbers.

Input  : arr[] = {0, 2, 8, 5, 2, 1, 4, 
                  13, 23};
Output : subset[] = {0, 2, 8, 5, 2, 1, 
                    13}
 
A simple solution is to iterate through all elements of given array. For every number, check if it is Fibonacci or not. If yes, add it to the result.
Python3
# python3 program to find largest Fibonacci subset# Prints largest subset of an array whose# all elements are fibonacci numbersdef findFibSubset(arr, n):  #Now iterate through all elements of the array..  for i in range(n):    #we are using the property of fibonacci series to check arr[i] is a    # fib number or not by checking whether any one out of 5(n^2)+4 and 5(n^2)-4    # is a perfect square or not.    fact1=5*(arr[i]**2)+4    fact2=5*(arr[i]**2)-4    if int(fact1**(.5))**2==fact1 or int(fact2**(.5))**2==fact2:      print(arr[i],end=" ")  return None                    # Driver codeif __name__ == "__main__":      arr = [4, 2, 8, 5, 20, 1, 40, 13, 23]    n = len(arr)    findFibSubset(arr, n)       # This code is contributed by Rajat Kumar (GLA University)
2 8 5 1 13 
Time complexity: Time complexity of the above solution is O(n) and space complexity is O(1).
Below is an another solution based on hashing.  
Find max in the arrayGenerate Fibonacci numbers till the max and store it in hash table.  Traverse array again if the number is present in hash table then add it to the result.
Find max in the array
Generate Fibonacci numbers till the max and store it in hash table.  
Traverse array again if the number is present in hash table then add it to the result.
 
C++
Java
Python3
C#
Javascript
// C++ program to find largest Fibonacci subset#include<bits/stdc++.h>using namespace std; // Prints largest subset of an array whose// all elements are fibonacci numbersvoid findFibSubset(int arr[], int n){    // Find maximum element in arr[]    int max = *std::max_element(arr, arr+n);     // Generate all Fibonacci numbers till    // max and store them in hash.    int a = 0, b = 1;    unordered_set<int> hash;    hash.insert(a);    hash.insert(b);    while (b < max)    {        int c = a + b;        a = b;        b = c;        hash.insert(b);    }     // Npw iterate through all numbers and    // quickly check for Fibonacci using    // hash.    for (int i=0; i<n; i++)        if (hash.find(arr[i]) != hash.end())            printf("%d ", arr[i]);} // Driver codeint main(){    int arr[] = {4, 2, 8, 5, 20, 1, 40, 13, 23};    int n = sizeof(arr)/sizeof(arr[0]);    findFibSubset(arr, n);    return 0;}
// Java program to find// largest Fibonacci subsetimport java.util.*; class GFG{    // Prints largest subset of an array whose    // all elements are fibonacci numbers    public static void findFibSubset(Integer[] x)    {        Integer max = Collections.max(Arrays.asList(x));        List<Integer> fib = new ArrayList<Integer>();        List<Integer> result = new ArrayList<Integer>();                 // Generate all Fibonacci numbers        // till max and store them        Integer a = 0;        Integer b = 1;        while (b < max){            Integer c = a + b;            a=b;            b=c;            fib.add(c);        }             // Now iterate through all numbers and        // quickly check for Fibonacci        for (Integer i = 0; i < x.length; i++){        if(fib.contains(x[i])){            result.add(x[i]);        }            }        System.out.println(result);    }     // Driver code    public static void main(String args[])    {        Integer[] a = {4, 2, 8, 5, 20, 1, 40, 13, 23};        findFibSubset(a);    }} // This code is contributed by prag93
# python3 program to find largest Fibonacci subset  # Prints largest subset of an array whose# all elements are fibonacci numbersdef findFibSubset(arr, n):     # Find maximum element in arr[]    m= max(arr)      # Generate all Fibonacci numbers till    # max and store them in hash.    a = 0    b = 1    hash = []    hash.append(a)    hash.append(b)    while (b < m):             c = a + b        a = b        b = c        hash.append(b)           # Npw iterate through all numbers and    # quickly check for Fibonacci using    # hash.    for i in range (n):        if arr[i] in hash :            print( arr[i],end=" ")  # Driver codeif __name__ == "__main__":     arr = [4, 2, 8, 5, 20, 1, 40, 13, 23]    n = len(arr)    findFibSubset(arr, n)
// C# program to find// largest Fibonacci subsetusing System;using System.Linq;using System.Collections.Generic;     class GFG{    // Prints largest subset of an array whose    // all elements are fibonacci numbers    public static void findFibSubset(int[] x)    {        int max = x.Max();        List<int> fib = new List<int>();        List<int> result = new List<int>();                 // Generate all Fibonacci numbers        // till max and store them        int a = 0;        int b = 1;        while (b < max)        {            int c = a + b;            a = b;            b = c;            fib.Add(c);        }             // Now iterate through all numbers and        // quickly check for Fibonacci        for (int i = 0; i < x.Length; i++)        {            if(fib.Contains(x[i]))            {                result.Add(x[i]);            }            }        foreach(int i in result)            Console.Write(i + " ");    }     // Driver code    public static void Main(String []args)    {        int[] a = {4, 2, 8, 5, 20, 1, 40, 13, 23};        findFibSubset(a);    }} // This code is contributed by PrinciRaj1992
<script>  // Javascript program to find largest Fibonacci subset // Prints largest subset of an array whose// all elements are fibonacci numbersfunction findFibSubset(arr, n){    // Find maximum element in arr[]    var max = arr.reduce((a,b)=>Math.max(a,b))     // Generate all Fibonacci numbers till    // max and store them in hash.    var a = 0, b = 1;    var hash = new Set();    hash.add(a);    hash.add(b);    while (b < max)    {        var c = a + b;        a = b;        b = c;        hash.add(b);    }     // Npw iterate through all numbers and    // quickly check for Fibonacci using    // hash.    for (var i=0; i<n; i++)        if (hash.has(arr[i]))            document.write( arr[i]            + " ");} // Driver codevar arr = [4, 2, 8, 5, 20, 1, 40, 13, 23];var n = arr.length;findFibSubset(arr, n); // This code is contributed by famously.</script>
2 8 5 1 13 
Time Complexity: Time complexity of above code is O(n) and space complexity will also be O(n) as we are storing it in hash map each fibonacci number in hashmap....
Reference : https://www.careercup.com/question?id=5154130839470080This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
prag93
ukasp
princiraj1992
famously
rajatkumargla19
Facebook
Fibonacci
subset
Arrays
Hash
Facebook
Arrays
Hash
Fibonacci
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)