Introduction
In this article, we will discuss yet another problem based on subarrays in a very interactive and intuitive way. We will start by brushing up on some important concepts that will help you understand the problem more effectively and easily. So, without much ado, let’s get started by seeing the prerequisites.
Pre-requisites
Some of the prerequisites required to solve this problem are as follows:
-
Subarray - A contiguous subsequence of an array is called a subarray.
Example - Given an array A = [1,2,3,5,6], some of the subarrays are [1],[2],[3],[6],[1,2,3], [3,5,6] etc.
-
Prime number- A number is said to be prime if it has only two factors, 1 and the number itself.
Example- 2,3,5,7,11 etc., are all prime numbers because they are not divisible by any other number than 1 and itself.
-
Sieve of Eratosthenes- When we talk about the prime numbers in coding, it comes with the need for a method by which we can check if a number is prime or not. Among many techniques, one such method is the Sieve of Eratosthenes, which helps us find all the prime numbers up to any given limit.
Example - If you want to find all primes in the range [1,n], we can use Sieve of Eratosthenes, which uses O(nloglogn) operations.
If you are not familiar with the concept of subarrays with a given sum, then you must read this article - What Is Subarray With Given Sum? to make the most out of this blog.
Let’s get started with the problem statement.
Problem Statement
You are given an array A[] of size N, consisting of positive integers, i.e. A[i]>=0, ∀ 0<=i<N. Find the length of the longest subarray having a prime sum.
What do you understand by “subarray having prime sum”?
A subarray A[i,j] is said to have prime sum if the sum of all the elements of this subarray is a prime number i.e. if S = A[i] + A[i+1] + … + A[j], then S is a prime number.
Why not look at a few examples with inputs and desired outputs for this problem statement!!
Example
Input:
array A[] = {1,2,3,7,11} N=5
Output:
4
Some of the subarrays of A[] = {1,2,3,7,11} having prime sum are:
- {3} → Sum=3
- {7} → Sum=7
- {11} → Sum=11
- {2} → Sum=2
- {2,3} → Sum=5
- {1,2} → Sum=3
- {1,2,3,7} → Sum=13
- {2,3,7,11} → Sum=23
Among all such subarrays, the maximum length is 4, and we have two subarrays having the maximum length and prime sum. Hence, the output is 4.
Please try to solve this problem on your own before moving on to further discussion here
In the next section, let’s move on to the approach and ideas about solving the problem.
Also see, Euclid GCD Algorithm