Longest sub-sequence of array containing Lucas numbers

Given an array arr[] of N elements, the task is to find the length of the longest sub-sequence in arr[] such that all the elements of the sequence are Lucas Numbers.


Input: arr[] = {2, 3, 55, 6, 1, 18}
Output: 4
1, 2, 3 and 18 are the only elements from the Lucas sequence.

Input: arr[] = {22, 33, 2, 123}
Output: 2


  • Find the maximum element in the array.
  • Generate Lucas numbers upto to the max and store them in a set.
  • Traverse the array arr[] and check if the current element is present in the set.
  • If it is present in the set, and increment the count.

Below is the implementation of the above approach:





// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the length of
// the longest required sub-sequence
int LucasSequence(int arr[], int n)
    // Find the maximum element from 
    // the array
    int max = *max_element(arr, arr+n);
    // Insert all lucas numbers
    // below max to the set
    // a and b are first two elements
    // of the Lucas sequence
    unordered_set<int> s;
    int a = 2, b = 1, c;
    while (b < max) {
        int c = a + b;
        a = b;
        b = c;
    int count = 0;
    for (int i = 0; i < n; i++) {
        // If current element is a Lucas 
        // number, increment count
        auto it = s.find(arr[i]);
        if (it != s.end()) 
    // Return the count
    return count;
// Driver code
int main()
    int arr[] = { 7, 11, 22, 4, 2, 1, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << LucasSequence(arr, n);
    return 0;




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.

Improved By : SURENDRA_GANGWAR, Ryuga

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.