Given an array A[] of length N, the task is to find the number of subarrays made up of only prime numbers.
Examples:
Input:_ arr[] = {2, 3, 4, 5, 7}_
Output:_ 6_
Explanation:
All possible subarrays made up of only prime numbers are {{2}, {3}, {2, 3}, {5}, {7}, {5, 7}}
Input:_ arr[] = {2, 3, 5, 6, 7, 11, 3, 5, 9, 3}_
Output:_ 17_
Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays from the given array and check if it made up of only prime numbers or not.
Time Complexity:_ O(N3 * √max(array)), where √M is the time required to check if a number is prime or not and this M can range **[min(arr), max(arr)]_**
Auxiliary Space:_ O(1)_
Efficient Approach: The following observation needs to be made to optimize the above approach:
_Count of subarrays from an array of length M is equal to _M * (M + 1) / 2.
Therefore, from a given array, a contiguous subarray of length M consisting only of primes will generate M * (M + 1) / 2 subarrays of length.
Follow the steps below to solve the problem:
Below the implementation of the above approach:
filter_none
edit
play_arrow
brightness_4
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
// Function to check if a number
// is prime or not.
**bool**
is_prime(``**int**
n)
{
**if**
(n <= 1)
**return**
0;
**for**
(``**int**
i = 2; i * i <= n; i++) {
// If n has any factor other than 1,
// then n is non-prime.
**if**
(n % i == 0)
**return**
0;
}
**return**
1;
}
// Function to return the count of
// subarrays made up of prime numbers only
**int**
count_prime_subarrays(``**int**
ar[],
**int**
n)
{
// Stores the answer
**int**
ans = 0;
// Stores the count of continous
// prime numbers in an array
**int**
count = 0;
**for**
(``**int**
i = 0; i < n; i++) {
// If the current array
// element is prime
**if**
(is_prime(ar[i]))
// Increase the count
count++;
**else**
{
**if**
(count) {
// Update count of subarrays
ans += count * (count + 1)
/ 2;
count = 0;
}
}
}
// If the array ended with a
// continous prime sequence
**if**
(count)
ans += count * (count + 1) / 2;
**return**
ans;
}
// Driver Code
**int**
main()
{
**int**
N = 10;
**int**
ar[] = { 2, 3, 5, 6, 7,
11, 3, 5, 9, 3 };
cout << count_prime_subarrays(ar, N);
}
Output:
17
_Time Complexity: _O(N * √max(arr)), where √M is the time required to check if a number is prime or not and this M can range **[min(arr), max(arr)]**
Auxiliary Space:_ O(1)_
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.
#arrays #mathematical #searching #prime number #subarray