Saturday, August 30, 2025
HomeData Modelling & AILength of Longest Prime Subsequence in an Array

Length of Longest Prime Subsequence in an Array

Given an array arr containing non-negative integers, the task is to print the length of the longest subsequence of prime numbers in the array.
Examples: 
 

Input: arr[] = { 3, 4, 11, 2, 9, 21 } 
Output:
Longest Prime Subsequence is {3, 2, 11} and hence the answer is 3.
Input: arr[] = { 6, 4, 10, 13, 9, 25 } 
Output:
 

 

Approach:

  • Traverse the given array.
  • For each element in the array, check if it prime or not.
  • If the element is prime, it will be in Longest Prime Subsequence. Hence, increment the required length of Longest Prime Subsequence by 1

Below is the implementation of the above approach: 
 

C++




// C++ program to find the length of
// Longest Prime Subsequence in an Array
 
#include <bits/stdc++.h>
using namespace std;
#define N 100005
 
// Function to create Sieve
// to check primes
void SieveOfEratosthenes(
    bool prime[], int p_size)
{
 
    // False here indicates
    // that it is not prime
    prime[0] = false;
    prime[1] = false;
 
    for (int p = 2; p * p <= p_size; p++) {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p]) {
 
            // Update all multiples of p,
            // set them to non-prime
            for (int i = p * 2;
                 i <= p_size;
                 i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the longest subsequence
// which contain all prime numbers
int longestPrimeSubsequence(int arr[], int n)
{
    bool prime[N + 1];
    memset(prime, true, sizeof(prime));
 
    // Precompute N primes
    SieveOfEratosthenes(prime, N);
 
    int answer = 0;
 
    // Find the length of
    // longest prime subsequence
    for (int i = 0; i < n; i++) {
        if (prime[arr[i]]) {
            answer++;
        }
    }
 
    return answer;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 4, 11, 2, 9, 21 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << longestPrimeSubsequence(arr, n)
         << endl;
 
    return 0;
}


Java




// Java program to find the length of
// Longest Prime Subsequence in an Array
import java.util.*;
 
class GFG
{
static final int N = 100005;
  
// Function to create Sieve
// to check primes
static void SieveOfEratosthenes(
    boolean prime[], int p_size)
{
  
    // False here indicates
    // that it is not prime
    prime[0] = false;
    prime[1] = false;
  
    for (int p = 2; p * p <= p_size; p++) {
  
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p]) {
  
            // Update all multiples of p,
            // set them to non-prime
            for (int i = p * 2;
                 i <= p_size;
                 i += p)
                prime[i] = false;
        }
    }
}
  
// Function to find the longest subsequence
// which contain all prime numbers
static int longestPrimeSubsequence(int arr[], int n)
{
    boolean []prime = new boolean[N + 1];
    Arrays.fill(prime, true);
  
    // Precompute N primes
    SieveOfEratosthenes(prime, N);
  
    int answer = 0;
  
    // Find the length of
    // longest prime subsequence
    for (int i = 0; i < n; i++) {
        if (prime[arr[i]]) {
            answer++;
        }
    }
  
    return answer;
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 4, 11, 2, 9, 21 };
    int n = arr.length;
  
    // Function call
    System.out.print(longestPrimeSubsequence(arr, n)
         +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python 3 program to find the length of
# Longest Prime Subsequence in an Array
N = 100005
  
# Function to create Sieve
# to check primes
def SieveOfEratosthenes(prime,  p_size):
  
    # False here indicates
    # that it is not prime
    prime[0] = False
    prime[1] = False
  
    p = 2
    while  p * p <= p_size:
  
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p]):
  
            # Update all multiples of p,
            # set them to non-prime
            for i in range( p * 2, p_size + 1, p):
                prime[i] = False
 
        p += 1
       
# Function to find the longest subsequence
# which contain all prime numbers
def longestPrimeSubsequence( arr, n):
    prime = [True]*(N + 1)
  
    # Precompute N primes
    SieveOfEratosthenes(prime, N)
  
    answer = 0
  
    # Find the length of
    # longest prime subsequence
    for i in range (n):
        if (prime[arr[i]]):
            answer += 1
  
    return answer
  
# Driver code
if __name__ == "__main__":
    arr = [ 3, 4, 11, 2, 9, 21 ]
    n = len(arr)
  
    # Function call
    print (longestPrimeSubsequence(arr, n))
 
# This code is contributed by chitranayal


C#




// C# program to find the length of
// longest Prime Subsequence in an Array
using System;
 
class GFG
{
static readonly int N = 100005;
   
// Function to create Sieve
// to check primes
static void SieveOfEratosthenes(
    bool []prime, int p_size)
{
   
    // False here indicates
    // that it is not prime
    prime[0] = false;
    prime[1] = false;
   
    for (int p = 2; p * p <= p_size; p++) {
   
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p]) {
   
            // Update all multiples of p,
            // set them to non-prime
            for (int i = p * 2;
                 i <= p_size;
                 i += p)
                prime[i] = false;
        }
    }
}
   
// Function to find the longest subsequence
// which contain all prime numbers
static int longestPrimeSubsequence(int []arr, int n)
{
    bool []prime = new bool[N + 1];
    for (int i = 0; i < N+1; i++)
        prime[i] = true;
   
    // Precompute N primes
    SieveOfEratosthenes(prime, N);
   
    int answer = 0;
   
    // Find the length of
    // longest prime subsequence
    for (int i = 0; i < n; i++) {
        if (prime[arr[i]]) {
            answer++;
        }
    }
   
    return answer;
}
   
// Driver code
public static void Main(String[] args)
{
    int []arr = { 3, 4, 11, 2, 9, 21 };
    int n = arr.Length;
   
    // Function call
    Console.Write(longestPrimeSubsequence(arr, n)
         +"\n");
}
}
  
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript program to find the length of
// Longest Prime Subsequence in an Array
 
let N = 100005
 
// Function to create Sieve
// to check primes
function SieveOfEratosthenes(prime, p_size)
{
 
    // False here indicates
    // that it is not prime
    prime[0] = false;
    prime[1] = false;
 
    for (let p = 2; p * p <= p_size; p++) {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p]) {
 
            // Update all multiples of p,
            // set them to non-prime
            for (let i = p * 2;
                i <= p_size;
                i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the longest subsequence
// which contain all prime numbers
function longestPrimeSubsequence(arr, n)
{
    let prime = new Array(N + 1);
    prime.fill(true)
 
    // Precompute N primes
    SieveOfEratosthenes(prime, N);
 
    let answer = 0;
 
    // Find the length of
    // longest prime subsequence
    for (let i = 0; i < n; i++) {
        if (prime[arr[i]]) {
            answer++;
        }
    }
 
    return answer;
}
 
// Driver code
 
let arr = [ 3, 4, 11, 2, 9, 21 ];
let n = arr.length
 
// Function call
document.write(longestPrimeSubsequence(arr, n) + "<br>");
 
// This code is contributed by gfgking
 
</script>


Output

3

Time Complexity: O(N log (log N)) 

Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11839 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7014 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6703 POSTS0 COMMENTS