Count of subarrays consisting of only prime numbers | C ++ Program to implement the above approach ; Function to check if a number is prime or not . ; If n has any factor other than 1 , then n is non - prime . ; Function to return the count of subarrays made up of prime numbers only ; Stores the answer ; Stores the count of continuous prime numbers in an array ; If the current array element is prime ; Increase the count ; Update count of subarrays ; If the array ended with a continuous prime sequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_prime ( int n ) { if ( n <= 1 ) return 0 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return 0 ; } return 1 ; } int count_prime_subarrays ( int ar [ ] , int n ) { int ans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( is_prime ( ar [ i ] ) ) count ++ ; else { if ( count ) { ans += count * ( count + 1 ) / 2 ; count = 0 ; } } } if ( count ) ans += count * ( count + 1 ) / 2 ; return ans ; } int main ( ) { int N = 10 ; int ar [ ] = { 2 , 3 , 5 , 6 , 7 , 11 , 3 , 5 , 9 , 3 } ; cout << count_prime_subarrays ( ar , N ) ; }