Count subarrays with Prime sum in C++

C++Server Side ProgrammingProgramming

We are given an array of positive integers. The goal is to find the subarrays of numbers in an array such that each subarray has the sum as prime. If the array is { 1,2,3,4 }. Then subarrays will be {1,2}, {2,3}, {3,4}. Count of such subarrays is 3.

Let us understand with examples

Input − arr[] = {1,3,5,3,2 };

Output − Count of subarrays with Prime sum are: 3

Explanation − Subarrays will be : { 3,2} sum=5 prime, {3,5,3} sum=11 prime and {3,5,3,2} sum is 13 prime.

Input − arr[] = {2,4,6 };

Output − Count of subarrays with prime sum are: 0

Explanation − All subarrays have non-prime sums. {2,4}=6, {4,6}=10

The approach used in the below program is as follows

We will find all prime numbers less than a maximum value 107 using a sieve and store it in vector<bool> check. If any number is prime then check[i] is true else false. Then traverse the array using two for loops, keep adding elements in the sum of subarray and check if it is prime using check[sum]. If yes then increment the count for subarrays with prime sum.

  • Take an array arr[] of positive integers.

  • Function sub_prime(int arr[], int size) takes the array and returns the count of subarrays with sum is prime.

  • Take the initial count as 0.

  • Initialize temp=pow(10,7) as maximum value.

  • Initialize the vector check with true.

  • check[0] and check[1] are false as they are non-prime.

  • From i=2 to i*i<temp. All numbers will be false as these will be non-primes.

  • Now vector check[i] is true if i is prime else false.

  • Traverse array again using two for loops.

  • Take variable total as sum of elements in subarray. Arr[i] to arr[j]. Where i=0 to i<size-1 and j=i+1 to j<size.

  • If any check[total] is true. ( sum total is prime ). Increment count.

  • Return count at the end of all loops as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int sub_prime(int arr[], int size){
   int count = 0;
   int temp = int(pow(10, 7));
   vector check(temp + 1, true);
   check[0] = false;
   check[1] = false;
   for (int i = 2; i * i <= temp; i++){
      if (check[i] == true){
         for (int j = i * 2; j <= temp; j += i){
            check[j] = false;
         }
      }
   }
   for (int i = 0; i < size - 1; ++i){
      int total = arr[i];
      for (int j = i + 1; j < size; ++j){
         total += arr[j];
         if (check[total]){
            ++count;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 3, 5, 1, 9, 5 };
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of subarrays with Prime sum are: "<<sub_prime(arr, size);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of subarrays with Prime sum are: 1
raja
Published on 01-Dec-2020 16:51:33
Advertisements