Largest subset whose all elements are Fibonacci numbers (original) (raw)
Last Updated : 09 Dec, 2024
Given an array arr[], the task is to find the largest subset from array that contain elements which are**Fibonacci numbers.**
**Examples :
**Input: arr[] = [1, 4, 3, 9, 10, 13, 7]
**Output: [1, 3, 13]
**Explanation: The output three numbers are the only Fibonacci numbers in array.**Input: arr[] = [0, 2, 8, 5, 2, 1, 4, 13, 23]
**Output: [0, 2, 8, 5, 2, 1, 13]
**Explanation: The output numbers are the only Fibonacci numbers in array.
Table of Content
- [Naive Approach] Using Hash Set – O(n) Time and O(n) Space
- [Expected Approach] Using Mathematical Formulae – O(n log m) Time and O(1) Space
**[Naive Approach] Using Hash Set – O(n) Time and O(n) Space
A **simple solution is to use a **Hash Set. Firstly traverse the array to **find the max element in the array, Then generate all the Fibonacci numbers smaller than **max element and store them in **Hash Set. Now traverse the array and check if that element is there in the **Hash set or not. If Yes, put it in the result array.
C++ `
// C++ program to find largest Fibonacci subset // Using Hash set #include #include #include #include using namespace std;
// Prints largest subset of an array whose // all elements are fibonacci numbers vector findFibSubset(vector &arr){ int n = arr.size();
// Find maximum element in arr[]
int max = *max_element(arr.begin(), arr.end());
// Generate all Fibonacci numbers till
// max and store them in hash.
int a = 0, b = 1;
unordered_set<int> st;
st.insert(a);
st.insert(b);
while (b < max){
int c = a + b;
a = b;
b = c;
st.insert(b);
}
vector<int> res;
// Now iterate through all numbers and
// quickly check for Fibonacci using hash.
for (int i = 0; i < n; i++)
if (st.find(arr[i]) != st.end())
res.push_back(arr[i]);
return res;
}
// Driver code int main() { vector arr = {4, 2, 8, 5, 20, 1, 40, 13, 23}; vector res= findFibSubset(arr); for (int i = 0; i < res.size(); i++) cout<< res[i] << " "; cout << endl; return 0; }
Java
// Java program to find largest Fibonacci subset // Using Hash set import java.util.ArrayList; import java.util.HashSet; import java.util.Set;
class GfG {
// Function to find the largest Fibonacci subset
static ArrayList<Integer> findFibSubset(int arr[]) {
// Find maximum element in arr[]
int max = Integer.MIN_VALUE;
for (int num : arr) {
if (num > max) {
max = num;
}
}
// Generate all Fibonacci numbers till max and store them in a hash set
int a = 0, b = 1;
Set<Integer> st = new HashSet<>();
st.add(a);
st.add(b);
while (b < max) {
int c = a + b;
a = b;
b = c;
st.add(b);
}
// Find all numbers in arr[] that are Fibonacci numbers
ArrayList<Integer> res = new ArrayList<>();
for (int num : arr) {
if (st.contains(num)) {
res.add(num);
}
}
return res;
}
public static void main(String[] args) {
int arr[] = {4, 2, 8, 5, 20, 1, 40, 13, 23};
ArrayList<Integer> res = findFibSubset(arr);
for (int num : res) {
System.out.print(num + " ");
}
System.out.println();
}
}
Python
Python Program to find largest fibonacci subsegment
Using Hash set
def findFibSubset(arr):
# Create a set to store Fibonacci numbers
hs = {0, 1}
# Find the maximum value in the input list
mx = max(arr)
# Generate Fibonacci numbers and store them in a set
x, y, z = 0, 1, 0
while z <= mx:
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
if name == "main": a = [4, 2, 8, 5, 20, 1, 40, 13, 23] ans = findFibSubset(a) print(' '.join(map(str, ans)))
C#
// C# program to find largest Fibonacci subset // Using Hash set using System; using System.Linq; using System.Collections.Generic;
class GfG {
// Finds the largest subset of an array whose
// all elements are Fibonacci numbers
static List<int> findFibSubset(int[] arr) {
int max = arr.Max();
// Generate all Fibonacci numbers till max
// and store them in a hash set
HashSet<int> st = new HashSet<int>();
int a = 0, b = 1;
st.Add(a);
st.Add(b);
while (b < max) {
int c = a + b;
a = b;
b = c;
st.Add(b);
}
// Iterate through the array and check if the
// element is in the Fibonacci set
List<int> res = new List<int>();
foreach(int num in arr) {
if (st.Contains(num)) {
res.Add(num);
}
}
return res;
}
// Driver code
static void Main(string[] args) {
int[] arr = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
List<int> res = findFibSubset(arr);
foreach(int num in res)
Console.Write(num + " ");
Console.WriteLine();
}
}
JavaScript
// Javascript program to find largest Fibonacci subset // Using Hash set function findFibSubset(arr) {
// Create a Set to store Fibonacci numbers
const st = new Set();
st.add(0);
st.add(1);
// Find the maximum value in the input array
let mx = 0;
for (let i = 0; i < arr.length; i++) {
mx = Math.max(arr[i], mx);
}
// Generate Fibonacci numbers and store them in a Set
let a = 0, b = 1, c = 0;
while (c <= mx) {
c = a + b;
st.add(c);
a = b;
b = c;
}
// Check the array elements for Fibonacci number
const res = [];
for (let i = 0; i < arr.length; i++) {
if (st.has(arr[i])) {
res.push(arr[i]);
}
}
return res;
}
// Driver Code const arr = [4, 2, 8, 5, 20, 1, 40, 13, 23]; const res = findFibSubset(arr); console.log(res.join(' '));
`
[Expected Approach] Using Mathematical Formulae – O(n log m) Time and O(1) Space
A number
n
is a Fibonacci number **if and only if one or both of the following conditions hold true:
- **5 × (n^2) + 4 is a **perfect square, or
- **5 × (n^2) − 4 is a **perfect square.
This property is derived from the fact that **Fibonacci numbers have a specific relationship with certain **quadratic forms. It is based on number theory and is a very efficient way to check if a number belongs to the Fibonacci sequence without having to generate the Fibonacci numbers.
C++ `
// C++ program to find largest Fibonacci subset // Using Mathematical Formulae #include #include #include using namespace std;
// Function to check if a number is Fibonacci bool isFibonacci(int num) {
// Using the property that a number is Fibonacci if and
//only if one of 5*n^2 + 4 or 5*n^2 - 4 is a perfect square.
int fact1 = 5 * num * num + 4;
int fact2 = 5 * num * num - 4;
int sqrtFact1 = (int) sqrt(fact1);
int sqrtFact2 = (int) sqrt(fact2);
return (sqrtFact1 * sqrtFact1 == fact1 ||
sqrtFact2 * sqrtFact2 == fact2);
}
// Function to find the largest Fibonacci subset vector findFibSubset(vector arr) { vector res;
// Iterate through all elements of the array
for (int i = 0; i < arr.size(); i++) {
if (isFibonacci(arr[i])) {
res.push_back(arr[i]);
}
}
return res;
}
int main() { vector arr = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; vector res = findFibSubset(arr);
for (int num : res) {
cout << num << " ";
}
cout << endl;
return 0;
}
Java
// Java program to find largest Fibonacci subset // Using Mathematical Formulae import java.util.ArrayList; class GfG {
// Function to check if a number is Fibonacci
static boolean isFibonacci(int num) {
// Using the property that a number is Fibonacci if and only if
// one of (5 * n^2 + 4) or (5 * n^2 - 4) is a perfect square.
int fact1 = 5 * num * num + 4;
int fact2 = 5 * num * num - 4;
int sqrtFact1 = (int) Math.sqrt(fact1);
int sqrtFact2 = (int) Math.sqrt(fact2);
return (sqrtFact1 * sqrtFact1 == fact1 ||
sqrtFact2 * sqrtFact2 == fact2);
}
// Function to find the largest Fibonacci subset
static public ArrayList<Integer> findFibSubset(int arr[]) {
ArrayList<Integer> res = new ArrayList<>();
// Iterate through all elements of the array
for (int num : arr) {
if (isFibonacci(num)) {
res.add(num);
}
}
return res;
}
// Driver code
public static void main(String[] args) {
int arr[] = {4, 2, 8, 5, 20, 1, 40, 13, 23};
ArrayList<Integer> res = findFibSubset(arr);
for (int num : res) {
System.out.print(num + " ");
}
System.out.println();
}
}
` Python ``
python3 program to find largest Fibonacci subset
Using Mathematical Formulae
def findFibSubset(arr): res = []
# Iterate through all elements of the array
for num in arr:
# Using the property of Fibonacci series to check if `num` is a Fibonacci number
fact1 = 5 * (num ** 2) + 4
fact2 = 5 * (num ** 2) - 4
if int(fact1**0.5)**2 == fact1 or int(fact2**0.5)**2 == fact2:
res.append(num)
return res
Driver code
if name == "main": arr = [4, 2, 8, 5, 20, 1, 40, 13, 23] res = findFibSubset(arr)
# Print the result
print(" ".join(map(str, res)))
`` C# `
// C# program to find largest Fibonacci subset // Using Mathematical Formulae using System; using System.Linq; using System.Collections.Generic; class GfG {
// Function to check if a number is Fibonacci
static bool isFibonacci(int num) {
// Using the property that a number is Fibonacci if and only if
// one of 5*n^2 + 4 or 5*n^2 - 4 is a perfect square.
int fact1 = 5 * num * num + 4;
int fact2 = 5 * num * num - 4;
int sqrtFact1 = (int) Math.Sqrt(fact1);
int sqrtFact2 = (int) Math.Sqrt(fact2);
return (sqrtFact1 * sqrtFact1 == fact1 || sqrtFact2 * sqrtFact2 == fact2);
}
// Function to find the largest Fibonacci subset
static List<int> findFibSubset(int[] arr) {
List<int> res = new List<int>();
for (int i = 0; i < arr.Length; i++) {
if (isFibonacci(arr[i])) {
res.Add(arr[i]);
}
}
return res;
}
// Driver code
public static void Main(String[] args) {
int[] arr = { 4, 2, 8, 5, 20, 1, 40, 13, 23 };
List<int> res = findFibSubset(arr);
// Print the result
foreach (int num in res) {
Console.Write(num + " ");
}
Console.WriteLine();
}
}
JavaScript
// Javascript program to find largest Fibonacci subset // Using Mathematical Formulae function findFibSubset(arr) { let res = [];
// Iterate through all elements of the array
for (let i = 0; i < arr.length; i++) {
// Using the property that a number is Fibonacci if
// and only if one of 5*n^2 + 4 or 5*n^2 - 4 is a
// perfect square
let fact1 = 5 * Math.pow(arr[i], 2) + 4;
let fact2 = 5 * Math.pow(arr[i], 2) - 4;
if (Math.pow(Math.round(Math.sqrt(fact1)), 2) === fact1
|| Math.pow(Math.round(Math.sqrt(fact2)), 2) === fact2) {
res.push(arr[i]);
}
}
return res;
}
// Driver code let arr = [ 4, 2, 8, 5, 20, 1, 40, 13, 23 ]; let res = findFibSubset(arr); console.log(res.join(' '));
`
**Time Complexity: O(n * log m), where n is the size of the array and m is the maximum element of the array.
**Auxiliary Space: O(1)