Given an array A[] of integers. The task is to count total subarrays whose sum is prime with ( size > 1 ).
Examples:
Input : A[] = { 1, 2, 3, 4, 5 }
Output : 3
Subarrays are -> {1, 2}, {2, 3}, {3, 4}
Input : A = { 22, 33, 4, 1, 10 };
Output : 4
Approach: Generate all possible subarrays and store their sum in a vector. Iterate the vector and check whether a sum is prime or not. It YES increment the count.
You can use sieve-of-eratosthenes to check whether a sum is prime in O(1).
Below is the implementation of above approach:
C++
// C++ program to count subarrays // with Prime sum #include <bits/stdc++.h> using namespace std; // Function to count subarrays // with Prime sum int primeSubarrays(int A[], int n) { int max_val = int(pow(10, 7)); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } int cnt = 0; // Initialize result // Traverse through the array for (int i = 0; i < n - 1; ++i) { int val = A[i]; for (int j = i + 1; j < n; ++j) { val += A[j]; if (prime[val]) ++cnt; } } // return answer return cnt; } // Driver program int main() { int A[] = { 1, 2, 3, 4, 5 }; int n = sizeof(A) / sizeof(A[0]); cout << primeSubarrays(A, n); return 0; } |
Java
// Java program to count subarrays // with Prime sum import java.util.*; class Solution { // Function to count subarrays // with Prime sum static int primeSubarrays(int A[], int n) { int max_val = (int)(Math.pow(10, 7)); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. Vector<Boolean> prime=new Vector<Boolean>(max_val + 1); //initilize initial value for (int p = 0; p <max_val + 1; p++) prime.add(p,true); // Remaining part of SIEVE prime.set(0, false); prime.set(1, false); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime.get(p) == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.set(i, false); } } int cnt = 0; // Initialize result // Traverse through the array for (int i = 0; i < n - 1; ++i) { int val = A[i]; for (int j = i + 1; j < n; ++j) { val += A[j]; if (prime.get(val)) ++cnt; } } // return answer return cnt; } // Driver program public static void main(String args[]) { int A[] = { 1, 2, 3, 4, 5 }; int n = A.length; System.out.print( primeSubarrays(A, n)); } } //contributed by Arnab Kundu |
Python3
# Python3 program to count subarrays # with Prime sum # Function to count subarrays # with Prime sum def primeSubarrays(A, n): max_val = 10**7 # USE SIEVE TO FIND ALL PRIME NUMBERS # LESS THAN OR EQUAL TO max_val # Create a boolean array "prime[0..n]". A # value in prime[i] will finally be false # if i is Not a prime, else true. prime = [True] * (max_val + 1) # Remaining part of SIEVE prime[0] = False prime[1] = False for p in range(2, int(max_val**(0.5)) + 1): # If prime[p] is not changed, then # it is a prime if prime[p] == True: # Update all multiples of p for i in range(2 * p, max_val + 1, p): prime[i] = False cnt = 0 # Initialize result # Traverse through the array for i in range(0, n - 1): val = A[i] for j in range(i + 1, n): val += A[j] if prime[val] == True: cnt += 1 # return answer return cnt # Driver Code if __name__ == "__main__": A = [1, 2, 3, 4, 5] n = len(A) print(primeSubarrays(A, n)) # This code is contributed by Rituraj Jain |
C#
// C# program to count subarrays // with Prime sum class Solution { // Function to count subarrays // with Prime sum static int primeSubarrays(int[] A, int n) { int max_val = (int)(System.Math.Pow(10, 7)); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. bool[] prime=new bool[max_val + 1]; //initilize initial value for (int p = 0; p <max_val + 1; p++) prime[p]=true; // Remaining part of SIEVE prime[0]=false; prime[1]=false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i]=false; } } int cnt = 0; // Initialize result // Traverse through the array for (int i = 0; i < n - 1; ++i) { int val = A[i]; for (int j = i + 1; j < n; ++j) { val += A[j]; if (prime[val]) ++cnt; } } // return answer return cnt; } // Driver program static void Main() { int[] A = { 1, 2, 3, 4, 5 }; int n = A.Length; System.Console.WriteLine( primeSubarrays(A, n)); } } //contributed by mits |
PHP
<?php // PHP program to count subarrays // with Prime sum // Function to count subarrays // with Prime sum function primeSubarrays($A, $n) { $max_val = pow(10, 5); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. $prime=array_fill(0,$max_val + 1,true); // Remaining part of SIEVE $prime[0] = false; $prime[1] = false; for ($p = 2; $p * $p <= $max_val; $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $max_val; $i += $p) $prime[$i] = false; } } $cnt = 0; // Initialize result // Traverse through the array for ($i = 0; $i < $n - 1; ++$i) { $val = $A[$i]; for ($j = $i + 1; $j < $n; ++$j) { $val += $A[$j]; if ($prime[$val]) ++$cnt; } } // return answer return $cnt; } // Driver program $A = array( 1, 2, 3, 4, 5 ); $n = count($A); echo primeSubarrays($A, $n); // This code is contributed by mits ?> |
3
Time Complexity: O(N2)
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 all prime numbers in a given range whose sum of digits is also prime
- Count prime numbers that can be expressed as sum of consecutive prime numbers
- Count of subarrays having exactly K prime numbers
- Count of subarrays consisting of only prime numbers
- Count subarrays such that remainder after dividing sum of elements by K gives count of elements
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Prime numbers after prime P with sum S
- Sum of each element raised to (prime-1) % prime
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Check if a prime number can be expressed as sum of two Prime Numbers
- Check whether the sum of prime elements of the array is prime or not
- Print prime numbers with prime sum of digits in an array
- Sum of prime numbers without odd prime digits
- Count all subarrays whose sum can be split as difference of squares of two Integers
- Count of subarrays with sum at least K
- Count of total subarrays whose sum is a Fibonacci Numbers
- Count subarrays with sum as difference of squares of two numbers
- Count subarrays with non-zero sum in the given Array
- Count of subarrays whose sum is a perfect square
- Count subarrays with sum equal to its XOR value
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.

