c-plus-plus
  1. c-plus-plus-largest-subset-whose-all-elements-are-fibonacci-numbers

C++ Program to Find Largest Subset Whose All Elements are Fibonacci Numbers

In this program, we will find the largest subset of an array whose all elements are Fibonacci numbers.

Syntax

#include <bits/stdc++.h>
using namespace std;

bool isPerfectSquare(int x);

bool isFibonacci(int n);

void findFibSubset(int arr[], int n);

Example

#include <bits/stdc++.h>
using namespace std;

bool isPerfectSquare(int x) {
    int s = sqrt(x);
    return (s * s == x);
}

bool isFibonacci(int n) {
    return isPerfectSquare(5 * n * n + 4) ||
           isPerfectSquare(5 * n * n - 4);
}

void findFibSubset(int arr[], int n) {
    int max_val = INT_MIN;
    for (int i = 0; i < n; i++) {
        max_val = max(max_val, arr[i]);
    }
    int fib_arr[max_val + 1] = {0};
    for (int i = 1; i <= max_val; i++) {
        if (isFibonacci(i)) {
            fib_arr[i] = 1;
        }
    }
    int max_fib = 0, max_fib_len = 0;
    for (int i = 0; i < n; i++) {
        int len = 0, j = i;
        while (j < n && fib_arr[arr[j]]) {
            len++;
            j++;
        }
        if (len > max_fib_len) {
            max_fib_len = len;
            max_fib = i;
        }
    }
    if (max_fib_len == 0) {
        cout << "No Fibonacci Elements";
        return;
    }
    for (int i = max_fib; i < max_fib + max_fib_len; i++) {
        cout << arr[i] << " ";
    }
}

int main() {
    int arr[] = {1, 4, 7, 8, 10, 13, 14, 15, 23};
    int n = sizeof(arr) / sizeof(arr[0]);
    findFibSubset(arr, n);
    return 0;
}

Output

1 8 13 

Explanation

In the above program, we first check if a number is Fibonacci or not using a helper function. Then we find the largest value in the array and create a new array to mark all the Fibonacci numbers until that value. We then iterate through the main array finding subsets whose elements are both present in the main array and Fibonacci numbers. Finally, we find the largest subset and print out the result.

Use

This program can be used to find the largest subset in an array whose elements are all Fibonacci numbers.

Important Points

  • We need to check if a given number is a Fibonacci number or not.
  • We need to create a new array to mark all the Fibonacci numbers until the largest value in the given array.
  • We need to iterate through the array finding subsets whose elements are both present in the main array and Fibonacci numbers.

Summary

In summary, we have learned how to find the largest subset in an array whose elements are all Fibonacci numbers. The program first checks if a number is a Fibonacci number or not and then iterates through the main array to find the largest subset with elements present in the main array and Fibonacci numbers.

Published on: