# Find longest subarray with Prime sum in given Array

• Difficulty Level : Easy
• Last Updated : 19 Sep, 2021

Given an array arr[], the task is to find the longest subarray whose sum is a prime number.

Examples:

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.

Input:   arr[ ] = {1, 4, 2, 1}
Output:  3
Explaination:  4+2+1=7 and 7 is a prime number thus the subarray we get is {4, 2, 1} .

Input: arr[ ] = {5, 2, 11, 4, 7, 19}
Output:  5
Explaination:  5+2+11+4+7=29 and 29 is a prime number thus the subarray we get is {5, 2, 11, 4, 7, 19} .

Approach: This problem can be solved by generating all subarrays and check for each subarray whether the sum is prime or not. For checking prime Sieve of Eratosthenes can be used. Any subarray can have a maximum sum equal to the sum of all the elements of the original array. Follow the steps to solve the given problem.

• Create a variable of total_sum which stores the sum of all the elements in the arr[].
• Do Sieve of Eratosthenes till total_sum because any subarray can’t have a sum greater than that.
• Create a max_sum variable to keep track of the maximum subarray we get while generating all the subarrays.
• Use two loops to find the sum of all the subarrays of arr[] and for each subarray, check whether the sum is prime or not.
• Take maximum among those subarrays whose sum is prime.
• Print max_sum as the required answer.

Below is the implementation of the above approach.

## C++

 `// C++ program for above approach``#include ``using` `namespace` `std;` `// Utility function to find whether number is``// prime or not``void` `SieveOfEratosthenes(``    ``vector<``bool``>& prime, ``int` `total_sum)``{``    ``// Create a boolean array "prime[0..n]" and``    ``// initialize all entries it as true.``    ``// A value in prime[i] will finally be false``    ``// if i is Not a prime, else true.``    ``for` `(``int` `i = 0; i <= total_sum; i++) {``        ``prime[i] = ``true``;``    ``}` `    ``for` `(``int` `p = 2; p * p <= total_sum; p++) {` `        ``// If prime[p] is not changed,``        ``// then it is a prime``        ``if` `(prime[p] == ``true``) {` `            ``// Update all multiples of p``            ``// greater than or equal to the square``            ``// of it numbers which are multiple of p``            ``// and are less than p^2 are already``            ``// been marked.``            ``for` `(``int` `i = p * p; i <= total_sum; i += p)``                ``prime[i] = ``false``;``        ``}``    ``}``}` `int` `maxLenSubarrayWithSumPrime(``    ``vector<``int``>& arr, ``int` `n)``{``    ``// to store total_sum of original array``    ``int` `total_sum = 0;` `    ``// calculate total_sum``    ``for` `(``int` `i = 0; i < n; i++) {``        ``total_sum += arr[i];``    ``}` `    ``// to store whether the number is``    ``// prime or not``    ``vector<``bool``> prime(total_sum + 1);` `    ``// calling sieve to get prime values``    ``SieveOfEratosthenes(prime, total_sum);` `    ``// to keep track of current and``    ``// maximum sum till now``    ``int` `max_sum = 0, cur_sum = 0;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``cur_sum = 0;``        ``for` `(``int` `j = i; j < n; j++) {``            ``cur_sum += arr[j];` `            ``// is current sum is prime``            ``if` `(prime[cur_sum]) {``                ``max_sum = max(max_sum, j - i + 1);``            ``}``        ``}``    ``}` `    ``// return maximum sum founded.``    ``return` `max_sum;``}` `// Driver Code``int` `main()``{``    ``int` `n = 6;``    ``vector<``int``> arr = { 5, 2, 11, 4, 7, 19 };` `    ``cout << maxLenSubarrayWithSumPrime(arr, n);``}`

## Java

 `// Java program for above approach``import` `java.util.*;` `class` `GFG{` `// Utility function to find whether number is``// prime or not``static` `void` `SieveOfEratosthenes(``    ``boolean` `[]prime, ``int` `total_sum)``{``  ` `    ``// Create a boolean array "prime[0..n]" and``    ``// initialize all entries it as true.``    ``// A value in prime[i] will finally be false``    ``// if i is Not a prime, else true.``    ``for` `(``int` `i = ``0``; i <= total_sum; i++) {``        ``prime[i] = ``true``;``    ``}` `    ``for` `(``int` `p = ``2``; p * p <= total_sum; p++) {` `        ``// If prime[p] is not changed,``        ``// then it is a prime``        ``if` `(prime[p] == ``true``) {` `            ``// Update all multiples of p``            ``// greater than or equal to the square``            ``// of it numbers which are multiple of p``            ``// and are less than p^2 are already``            ``// been marked.``            ``for` `(``int` `i = p * p; i <= total_sum; i += p)``                ``prime[i] = ``false``;``        ``}``    ``}``}` `static` `int` `maxLenSubarrayWithSumPrime(``    ``int``[] arr, ``int` `n)``{``    ``// to store total_sum of original array``    ``int` `total_sum = ``0``;` `    ``// calculate total_sum``    ``for` `(``int` `i = ``0``; i < n; i++) {``        ``total_sum += arr[i];``    ``}` `    ``// to store whether the number is``    ``// prime or not``    ``boolean` `[]prime = ``new` `boolean``[total_sum + ``1``];` `    ``// calling sieve to get prime values``    ``SieveOfEratosthenes(prime, total_sum);` `    ``// to keep track of current and``    ``// maximum sum till now``    ``int` `max_sum = ``0``, cur_sum = ``0``;``    ``for` `(``int` `i = ``0``; i < n; i++) {``        ``cur_sum = ``0``;``        ``for` `(``int` `j = i; j < n; j++) {``            ``cur_sum += arr[j];` `            ``// is current sum is prime``            ``if` `(prime[cur_sum]) {``                ``max_sum = Math.max(max_sum, j - i + ``1``);``            ``}``        ``}``    ``}` `    ``// return maximum sum founded.``    ``return` `max_sum;``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `n = ``6``;``    ``int` `[]arr = { ``5``, ``2``, ``11``, ``4``, ``7``, ``19` `};` `    ``System.out.print(maxLenSubarrayWithSumPrime(arr, n));``}``}` `// This code is contributed by shikhasingrajput.`

## Python3

 `# Python 3 program for above approach` `from` `math ``import` `sqrt``# Utility function to find whether number is``# prime or not``def` `SieveOfEratosthenes(prime, total_sum):``    ``# Create a boolean array "prime[0..n]" and``    ``# initialize all entries it as true.``    ``# A value in prime[i] will finally be false``    ``# if i is Not a prime, else true.``    ``for` `i ``in` `range``(total_sum``+``1``):``        ``prime[i] ``=` `True` `    ``for` `p ``in` `range``(``2``,``int``(sqrt(total_sum)),``1``):``        ``# If prime[p] is not changed,``        ``# then it is a prime``        ``if` `(prime[p] ``=``=` `True``):` `            ``# Update all multiples of p``            ``# greater than or equal to the square``            ``# of it numbers which are multiple of p``            ``# and are less than p^2 are already``            ``# been marked.``            ``for` `i ``in` `range``(p ``*` `p,total_sum``+``1``,p):``                ``prime[i] ``=` `False` `def` `maxLenSubarrayWithSumPrime(arr, n):``    ``# to store total_sum of original array``    ``total_sum ``=` `0` `    ``# calculate total_sum``    ``for` `i ``in` `range``(n):``        ``total_sum ``+``=` `arr[i]` `    ``# to store whether the number is``    ``# prime or not``    ``prime ``=` `[ ``False` `for` `i ``in` `range``(total_sum ``+` `1``)]` `    ``# calling sieve to get prime values``    ``SieveOfEratosthenes(prime, total_sum)` `    ``# to keep track of current and``    ``# maximum sum till now``    ``max_sum ``=` `0``    ``cur_sum ``=` `0``    ``for` `i ``in` `range``(n):``        ``cur_sum ``=` `0``        ``for` `j ``in` `range``(i,n,``1``):``            ``cur_sum ``+``=` `arr[j]` `            ``# is current sum is prime``            ``if` `(prime[cur_sum]):``                ``max_sum ``=` `max``(max_sum, j ``-` `i ``+` `1``)` `    ``# return maximum sum founded.``    ``return` `max_sum` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``n ``=` `6``    ``arr ``=` `[``5``, ``2``, ``11``, ``4``, ``7``, ``19``]``    ``print``(maxLenSubarrayWithSumPrime(arr, n))``    ` `    ``# This code is contributed by SURENDRA_GANGWAR.`

## C#

 `// C# program for above approach``using` `System;``class` `GFG {` `    ``// Utility function to find whether number is``    ``// prime or not``    ``static` `void` `SieveOfEratosthenes(``bool``[] prime,``                                    ``int` `total_sum)``    ``{` `        ``// Create a boolean array "prime[0..n]" and``        ``// initialize all entries it as true.``        ``// A value in prime[i] will finally be false``        ``// if i is Not a prime, else true.``        ``for` `(``int` `i = 0; i <= total_sum; i++) {``            ``prime[i] = ``true``;``        ``}` `        ``for` `(``int` `p = 2; p * p <= total_sum; p++) {` `            ``// If prime[p] is not changed,``            ``// then it is a prime``            ``if` `(prime[p] == ``true``) {` `                ``// Update all multiples of p``                ``// greater than or equal to the square``                ``// of it numbers which are multiple of p``                ``// and are less than p^2 are already``                ``// been marked.``                ``for` `(``int` `i = p * p; i <= total_sum; i += p)``                    ``prime[i] = ``false``;``            ``}``        ``}``    ``}` `    ``static` `int` `maxLenSubarrayWithSumPrime(``int``[] arr, ``int` `n)``    ``{``        ``// to store total_sum of original array``        ``int` `total_sum = 0;` `        ``// calculate total_sum``        ``for` `(``int` `i = 0; i < n; i++) {``            ``total_sum += arr[i];``        ``}` `        ``// to store whether the number is``        ``// prime or not``        ``bool``[] prime = ``new` `bool``[total_sum + 1];` `        ``// calling sieve to get prime values``        ``SieveOfEratosthenes(prime, total_sum);` `        ``// to keep track of current and``        ``// maximum sum till now``        ``int` `max_sum = 0, cur_sum = 0;``        ``for` `(``int` `i = 0; i < n; i++) {``            ``cur_sum = 0;``            ``for` `(``int` `j = i; j < n; j++) {``                ``cur_sum += arr[j];` `                ``// is current sum is prime``                ``if` `(prime[cur_sum]) {``                    ``max_sum = Math.Max(max_sum, j - i + 1);``                ``}``            ``}``        ``}` `        ``// return maximum sum founded.``        ``return` `max_sum;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``int` `n = 6;``        ``int``[] arr = { 5, 2, 11, 4, 7, 19 };` `        ``Console.WriteLine(``            ``maxLenSubarrayWithSumPrime(arr, n));``    ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``

Output
`5`

Time Complexity: O(N^2)
Auxiliary Complexity: O(N)

My Personal Notes arrow_drop_up