Count all sub-arrays having sum divisible by k

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the number of sub-arrays having sum divisible by k.

For this we will be provided with an array and a value k. Our task is to find the number of sub arrays that are having their sum as equal to the given value k.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//counting subarrays with k sum
int count_subarray(int arr[], int n, int k){
   int mod[k];
   memset(mod, 0, sizeof(mod));
   int cumSum = 0;
   for (int i = 0; i < n; i++) {
      cumSum += arr[i];
      //taking modulus to get positive sum
      mod[((cumSum % k) + k) % k]++;
   }
   int result = 0;
   for (int i = 0; i < k; i++)
      if (mod[i] > 1)
         result += (mod[i] * (mod[i] - 1)) / 2;
   result += mod[0];
   return result;
}
int main(){
   int arr[] = { 4, 5, 0, -2, -3, 1 };
   int k = 5;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << count_subarray(arr, n, k) << endl;
   int arr1[] = { 4, 5, 0, -12, -23, 1 };
   nt k1 = 5;
   int n1 = sizeof(arr1) / sizeof(arr1[0]);
   cout << count_subarray(arr1, n1, k1) << endl;
   return 0;
}

Output

7
7
raja
Published on 17-Feb-2020 10:31:47
Advertisements