Open In App
Related Articles

Largest subset whose all elements are Fibonacci numbers

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

Implementation:

C++

#include <bits/stdc++.h>
using namespace std;
void findFibSubset(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        int fact1 = 5 * pow(arr[i], 2) + 4;
        int fact2 = 5 * pow(arr[i], 2) - 4;
        if ((int)pow((int)pow(fact1, 0.5), 2) == fact1
            || (int)pow((int)pow(fact2, 0.5), 2) == fact2)
            cout << arr[i] << " ";
    }
}
 
int main()
{
    int arr[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
    int n = 9;
    findFibSubset(arr, n);
}
 
// This code is contributed by garg28harsh.

                    

Java

/*package whatever //do not write package name here */
import java.util.*;
class GFG {
 
  static void findFibSubset(int arr[], int n)
  {
    for(int i = 0; i < n; i++){
      int fact1 = 5 * (int)Math.pow(arr[i], 2) + 4;
      int fact2 = 5 * (int)Math.pow(arr[i], 2) - 4;
      if((int)Math.pow((int)Math.pow(fact1, 0.5), 2) == fact1 || (int)Math.pow((int)Math.pow(fact2, 0.5), 2) == fact2)
        System.out.print(arr[i] + " ");
    }
  }
 
  public static void main (String[] args) {
    int []arr = {4, 2, 8, 5, 20, 1, 40, 13, 23};
    int n = arr.length;
    findFibSubset(arr, n);
  }
}
 
// This code is contributed by aadityaburujwale.

                    

Python3

# python3 program to find largest Fibonacci subset
# Prints largest subset of an array whose
# all elements are fibonacci numbers
def 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 code
if __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)

                    

C#

using System;
class GFG {
  static void findFibSubset(int[] arr, int n)
  {
    for (int i = 0; i < n; i++) {
      int fact1 = 5 * (int)Math.Pow(arr[i], 2) + 4;
      int fact2 = 5 * (int)Math.Pow(arr[i], 2) - 4;
      if ((int)Math.Pow((int)Math.Pow(fact1, 0.5), 2)
          == fact1
          || (int)Math.Pow((int)Math.Pow(fact2, 0.5),
                           2)
          == fact2)
        Console.Write(arr[i] + " ");
    }
  }
  static void Main()
  {
    int[] arr = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
    int n = 9;
    findFibSubset(arr, n);
  }
}
 
// This code is contributed by garg28harsh.

                    

Javascript

function findFibSubset( arr,  n)
{
    let ans=[];
    for (let i = 0; i < n; i++) {
        let fact1 = 5 * Math.pow(arr[i], 2) + 4;
        let fact2 = 5 * Math.pow(arr[i], 2) - 4;
        if (Math.pow(Math.round(Math.pow(fact1, 0.5)), 2) == fact1  || Math.pow(Math.round(Math.pow(fact2, 0.5)), 2) == fact2)
            ans.push(arr[i]);
    }
    console.log(ans);
}
 
    let arr = [ 4, 2, 8, 5, 20, 1, 40, 13, 23 ];
    let n = 9;
    findFibSubset(arr, n);
     
    // This code is contributed by garg28harsh.

                    

Output
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. 

  1. Find max in the array
  2. Generate Fibonacci numbers till the max and store it in hash table. 
  3. Traverse array again if the number is present in hash table then add it to the result.

Implementation:

C++

// 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 numbers
void 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 code
int 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

// Java program to find
// largest Fibonacci subset
import 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

# python3 program to find largest Fibonacci subset
  
# Prints largest subset of an array whose
# all elements are fibonacci numbers
def 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 code
if __name__ == "__main__":
 
    arr = [4, 2, 8, 5, 20, 1, 40, 13, 23]
    n = len(arr)
    findFibSubset(arr, n)

                    

C#

// C# program to find
// largest Fibonacci subset
using 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

                    

Javascript

<script>
  
// Javascript program to find largest Fibonacci subset
 
// Prints largest subset of an array whose
// all elements are fibonacci numbers
function 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 code
var arr = [4, 2, 8, 5, 20, 1, 40, 13, 23];
var n = arr.length;
findFibSubset(arr, n);
 
// This code is contributed by famously.
</script>

                    

Output
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….

ANOTHER APPROACH USING HASH SET:

Intuition:

  1. We declare a HashSet<Integer> to store Fibonacci elements.
  2. Traverse the array to find the max element in the array.
  3. Iterate a loop from 0 to the max element and store all the Fibonacci elements in that range in HashSet., then run through the array if that element is there in the set or not, If Yes, put it in a data structure.
  4. At last return the data structure. 

Implementation:

C++

#include <bits/stdc++.h>
using namespace std;
 
// Function to find largest Fibonacci subset
vector<int> findFibSubset(int arr[], int n)
{
    unordered_set<int> hs;
    hs.insert(0);
    int maxZ = 0;
    int x = 0, y = 1, z = 0;
 
    // Find the value of max
    for (int i = 0; i < n; i++) {
        maxZ = max(arr[i], maxZ);
    }
 
    // Insert into HashSet
    for (int i = 0; z <= maxZ; i++) {
        z = x + y;
        hs.insert(z);
        x = y;
        y = z;
    }
    vector<int> ans;
    for (int i = 0; i < n; i++) {
        if (hs.find(arr[i]) != hs.end()) {
            ans.push_back(arr[i]);
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
    int a[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
    int len = sizeof(a)/sizeof(a[0]);
    vector<int> ans = findFibSubset(a, len);
 
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
}

                    

Java

// Java program to find largest Fibonacci subset
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find largest Fibonacci subset
    public static int[] findFibSubset(int arr[], int n)
    {
        HashSet<Integer> hs = new HashSet<>();
        hs.add(0);
        int maxZ = 0;
        int x = 0, y = 1, z = 0;
 
        // Find the value of max
        for (int i = 0; i < n; i++) {
            maxZ = Math.max(arr[i], maxZ);
        }
 
        // Insert into HashSet
        for (int i = 0; z <= maxZ; i++) {
            z = x + y;
            hs.add(z);
            x = y;
            y = z;
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (hs.contains(arr[i])) {
                list.add(arr[i]);
            }
        }
        int a = list.size();
        int[] ans = new int[a];
        for (int i = 0; i < a; i++) {
            ans[i] = list.get(i);
        }
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
        int len = a.length;
        int ans[] = findFibSubset(a, len);
 
        for (int i = 0; i < ans.length; i++) {
            System.out.print(ans[i] + " ");
        }
    }
}
// This code is contributed by Raunak Singh

                    

Python3

def find_fib_subset(arr):
    # Create a set to store Fibonacci numbers
    hs = {0, 1}
 
    # Find the maximum value in the input list
    max_z = max(arr)
 
    # Generate Fibonacci numbers and store them in a set
    x, y, z = 0, 1, 0
    while z <= max_z:
        z = x + y
        hs.add(z)
        x, y = y, z
 
    # Check if each element in the input list is a Fibonacci number
    ans = [num for num in arr if num in hs]
    return ans
 
# Driver Code
a = [4, 2, 8, 5, 20, 1, 40, 13, 23]
ans = find_fib_subset(a)
print(*ans)

                    

C#

using System;
using System.Collections.Generic;
 
class Program
{
    // Function to find the largest Fibonacci subset
    static List<int> FindFibSubset(int[] arr)
    {
        HashSet<int> hs = new HashSet<int> { 0, 1 };
        int maxZ = 0;
 
        // Find the maximum value in the input array
        foreach (int num in arr)
        {
            maxZ = Math.Max(num, maxZ);
        }
 
        int x = 0, y = 1, z = 0;
        List<int> fibList = new List<int> { 0, 1 };
 
        // Generate Fibonacci numbers and store them in a list
        while (z <= maxZ)
        {
            z = x + y;
            fibList.Add(z);
            hs.Add(z);
            x = y;
            y = z;
        }
 
        List<int> ans = new List<int>();
 
        // Check if each element in the input array is a Fibonacci number
        foreach (int num in arr)
        {
            if (hs.Contains(num))
            {
                ans.Add(num);
            }
        }
 
        return ans;
    }
 
    static void Main()
    {
        int[] a = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
        List<int> ans = FindFibSubset(a);
 
        Console.WriteLine(string.Join(" ", ans));
    }
}

                    

Javascript

// Function to find largest Fibonacci subset
function findFibSubset(arr) {
    // Create a Set to store Fibonacci numbers
    const hs = new Set();
    fib.add(0);
    fib.add(1);
 
    // Find the maximum value in the input array
    let maxZ = 0;
    for (let i = 0; i < arr.length; i++) {
        maxZ = Math.max(arr[i], maxZ);
    }
 
    // Generate Fibonacci numbers and store them in a Set
    let x = 0, y = 1, z = 0;
    while (z <= maxZ) {
        z = x + y;
        hs.add(z);
        x = y;
        y = z;
    }
 
    // Check if each element in the input array is a Fibonacci number
    const ans = [];
    for (let i = 0; i < arr.length; i++) {
        if (hs.has(arr[i])) {
            ans.push(arr[i]);
        }
    }
 
    return ans;
}
 
// Driver Code
const a = [4, 2, 8, 5, 20, 1, 40, 13, 23];
const ans = findFibSubset(a);
console.log(ans.join(' '));

                    

Output
2 8 5 1 13 

Time Complexity: O(N), since we traversing the array.

Space Complexity: O(N) since we using Hash Set to store fibonacci elements.

 



Last Updated : 20 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads