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:
- Traverse the array and for every element check if it is a prime or not.
- For every prime number found, keep incrementing count.
- For every non-prime element, update the required answer by adding count * (count + 1) / 2 and reset count to 0.
- Finally, print the required subarray.
Below the implementation of the above approach:
C++
// 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 onlyint 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 Codeint main(){ int N = 10; int ar[] = { 2, 3, 5, 6, 7, 11, 3, 5, 9, 3 }; cout << count_prime_subarrays(ar, N);} |
Java
// Java Program to implement// the above approachimport java.util.*;class GFG{// Function to check if a number// is prime or not.static boolean is_prime(int n){ if (n <= 1) return false; 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 false; } return true;}// Function to return the count of// subarrays made up of prime numbers onlystatic 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 != 0) { // Update count of subarrays ans += count * (count + 1) / 2; count = 0; } } } // If the array ended with a // continous prime sequence if (count != 0) ans += count * (count + 1) / 2; return ans;}// Driver Codepublic static void main(String[] args){ int N = 10; int []ar = { 2, 3, 5, 6, 7, 11, 3, 5, 9, 3 }; System.out.print(count_prime_subarrays(ar, N));}}// This code is contributed by PrinciRaj1992 |
Python3
# Python3 program to implement# the above approach# Function to check if a number# is prime or not.def is_prime(n): if(n <= 1): return 0 i = 2 while(i * i <= n): # If n has any factor other than 1, # then n is non-prime. if(n % i == 0): return 0 i += 1 return 1# Function to return the count of# subarrays made up of prime numbers onlydef count_prime_subarrays(ar, n): # Stores the answer ans = 0 # Stores the count of continous # prime numbers in an array count = 0 for i in range(n): # If the current array # element is prime if(is_prime(ar[i])): # Increase the count count += 1 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 CodeN = 10ar = [ 2, 3, 5, 6, 7, 11, 3, 5, 9, 3 ]# Function callprint(count_prime_subarrays(ar, N))# This code is contributed by Shivam Singh |
C#
// C# Program to implement// the above approachusing System;class GFG{// Function to check if a number// is prime or not.static bool is_prime(int n){ if (n <= 1) return false; 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 false; } return true;}// Function to return the count of// subarrays made up of prime numbers onlystatic 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 != 0) { // Update count of subarrays ans += count * (count + 1) / 2; count = 0; } } } // If the array ended with a // continous prime sequence if (count != 0) ans += count * (count + 1) / 2; return ans;}// Driver Codepublic static void Main(String[] args){ int N = 10; int []ar = { 2, 3, 5, 6, 7, 11, 3, 5, 9, 3 }; Console.Write(count_prime_subarrays(ar, N));}}// This code is contributed by Rajput-Ji |
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.
Recommended Posts:
- Count subarrays consisting of only 0's and only 1's in a binary array
- Count of substrings consisting only of vowels
- Count N-length strings consisting only of vowels sorted lexicographically
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Count prime numbers that can be expressed as sum of consecutive prime numbers
- Count numbers in a given range whose count of prime factors is a Prime Number
- Count numbers from range whose prime factors are only 2 and 3
- Count numbers from range whose prime factors are only 2 and 3 using Arrays | Set 2
- Count of subarrays having exactly K prime numbers
- Count N-digit numbers possible consisting of digits X and Y
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
- Count all prime numbers in a given range whose sum of digits is also prime
- Sort only non-prime numbers of an array in increasing order
- Length of longest subarray having only K distinct Prime Numbers
- Count of subarrays whose products don't have any repeating prime factor
- Count subarrays with Prime sum
- Count of subtrees from an N-ary tree consisting of single colored nodes
- Count of substrings consisting of even number of vowels
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

