Related Articles
Count of subarrays consisting of only prime numbers
• Difficulty Level : Medium
• Last Updated : 13 Apr, 2021

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:
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:

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 ``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);``}`

## Java

 `// Java Program to implement``// the above approach``import` `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 only``static` `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 Code``public` `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 only``def` `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 Code``N ``=` `10``ar ``=` `[ ``2``, ``3``, ``5``, ``6``, ``7``,``       ``11``, ``3``, ``5``, ``9``, ``3` `]` `# Function call``print``(count_prime_subarrays(ar, N))` `# This code is contributed by Shivam Singh`

## C#

 `// C# Program to implement``// the above approach``using` `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 only``static` `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 Code``public` `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`

## Javascript

 ``
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 mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up