Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Maximum no. of contiguous Prime Numbers in an array

  • Difficulty Level : Medium
  • Last Updated : 11 May, 2021

Given an array arr[] of N elements. The task is to find the maximum number of the contiguous prime numbers in the given array.
Examples: 

Input: arr[] = {3, 5, 2, 66, 7, 11, 8}
Output: 3
Maximum contiguous prime number sequence is {2, 3, 5}

Input: arr[] = {1, 0, 2, 11, 32, 8, 9}
Output: 2
Maximum contiguous prime number sequence is {2, 11}

Approach: 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

  • Create a sieve to check whether an element is prime or not in O(1).
  • Traverse the array with two variables named current_max and max_so_far.
  • If a prime number is found then increment current_max and compare it with max_so_far.
  • If current_max is greater than max_so_far, then assign max_so_far with current_max
  • Every time a non-prime element is found reset current_max to 0.

Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
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 * p; i <= p_size; i += p)
                prime[i] = false;
        }
    }
}
 
// Function that finds
// maximum contiguous subarray of prime numbers
int maxPrimeSubarray(int arr[], int n)
{
    int max_ele = *max_element(arr, arr+n);
    bool prime[max_ele + 1];
    memset(prime, true, sizeof(prime));
 
    SieveOfEratosthenes(prime, max_ele);
 
    int current_max = 0, max_so_far = 0;
 
    for (int i = 0; i < n; i++) {
 
        // check if element is non-prime
        if (prime[arr[i]] == false)
            current_max = 0;
 
        // If element is prime, than update
        // current_max and max_so_far accordingly.
        else {
            current_max++;
            max_so_far = max(current_max, max_so_far);
        }
    }
 
    return max_so_far;
}
 
// Driver code
int main()
{
 
    int arr[] = { 1, 0, 2, 4, 3, 29, 11, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxPrimeSubarray(arr, n);
 
    return 0;
}

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
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 * p; i <= p_size; i += p)
                prime[i] = false;
        }
    }
}
 
// Function that finds
// maximum contiguous subarray of prime numbers
static int maxPrimeSubarray(int arr[], int n)
{
    int max_ele = Arrays.stream(arr).max().getAsInt();
    boolean prime[] = new boolean[max_ele + 1];
    Arrays.fill(prime, true);
 
    SieveOfEratosthenes(prime, max_ele);
 
    int current_max = 0, max_so_far = 0;
 
    for (int i = 0; i < n; i++)
    {
        // check if element is non-prime
        if (prime[arr[i]] == false)
            current_max = 0;
 
        // If element is prime, than update
        // current_max and max_so_far accordingly.
        else
        {
            current_max++;
            max_so_far = Math.max(current_max, max_so_far);
        }
    }
    return max_so_far;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 0, 2, 4, 3, 29, 11, 7, 8, 9 };
    int n = arr.length;
    System.out.print(maxPrimeSubarray(arr, n));
}
}
 
/* This code contributed by PrinciRaj1992 */

Python 3




# Python3 implementation of
# the approach
 
def SieveOfEratosthenes( prime, p_size):
 
    # false here indicates
    # that it is not prime
    prime[0] = False
    prime[1] = False
    for p in range(2,p_size+1):
        if(p*p>p_size):
            break
 
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p]):
 
            # Update all multiples of p,
            # set them to non-prime
            i=p*p
            while(i<=p_size):
                prime[i] = False
                i = i + p
         
# Function that finds
# maximum contiguous subarray of prime numbers
def maxPrimeSubarray( arr, n):
 
    max_ele = max(arr)
    prime=[True]*(max_ele + 1)
 
    SieveOfEratosthenes(prime, max_ele)
 
    current_max = 0
    max_so_far = 0
    for i in range(n):
 
        # check if element is non-prime
        if (prime[arr[i]] == False):
            current_max = 0
 
        # If element is prime, than update
        # current_max and max_so_far accordingly.
        else:
            current_max=current_max + 1
            max_so_far = max(current_max, max_so_far)
         
    return max_so_far
 
# Driver code
if __name__=='__main__':
    arr = [ 1, 0, 2, 4, 3, 29, 11, 7, 8, 9 ]
    n = len(arr)
    print(maxPrimeSubarray(arr, n))
 
# this code is contributed by
# ash264

C#




// C# implementation of the approach
using System;
using System.Linq;
 
class GFG
{
 
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 * p; i <= p_size; i += p)
                prime[i] = false;
        }
    }
}
 
// Function that finds maximum
// contiguous subarray of prime numbers
static int maxPrimeSubarray(int []arr, int n)
{
    int max_ele = arr.Max();
    bool []prime = new bool[max_ele + 1];
    for(int i = 0; i < max_ele + 1; i++)
        prime[i]=true;
 
    SieveOfEratosthenes(prime, max_ele);
 
    int current_max = 0, max_so_far = 0;
 
    for (int i = 0; i < n; i++)
    {
        // check if element is non-prime
        if (prime[arr[i]] == false)
            current_max = 0;
 
        // If element is prime, than update
        // current_max and max_so_far accordingly.
        else
        {
            current_max++;
            max_so_far = Math.Max(current_max, max_so_far);
        }
    }
    return max_so_far;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 0, 2, 4, 3, 29, 11, 7, 8, 9 };
    int n = arr.Length;
    Console.Write(maxPrimeSubarray(arr, n));
}
}
 
// This code contributed by Rajput-Ji

Javascript




<script>
 
// Javascript implementation of the approach
 
function SieveOfEratosthenes(prime, p_size)
{
    // false here indicates
    // that it is not prime
    prime[0] = false;
    prime[1] = false;
 
    for (var 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 (var i = p * p; i <= p_size; i += p)
                prime[i] = false;
        }
    }
}
 
// Function that finds
// maximum contiguous subarray of prime numbers
function maxPrimeSubarray(arr, n)
{
    var max_ele = arr.reduce((a,b) => Math.max(a,b));
    var prime = Array(max_ele+1).fill(true);
 
    SieveOfEratosthenes(prime, max_ele);
 
    var current_max = 0, max_so_far = 0;
 
    for (var i = 0; i < n; i++) {
 
        // check if element is non-prime
        if (prime[arr[i]] == false)
            current_max = 0;
 
        // If element is prime, than update
        // current_max and max_so_far accordingly.
        else {
            current_max++;
            max_so_far = Math.max(current_max, max_so_far);
        }
    }
 
    return max_so_far;
}
 
// Driver code
var arr = [ 1, 0, 2, 4, 3, 29, 11, 7, 8, 9 ];
var n = arr.length;
document.write( maxPrimeSubarray(arr, n));
 
</script>
Output
4



My Personal Notes arrow_drop_up
Recommended Articles
Page :