- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count all sub-arrays having sum divisible by k
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
#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
- Related Articles
- Count sub-matrices having sum divisible 'k' in C++
- Count all sub-sequences having product
- Count pairs from two arrays having sum equal to K in C++
- Count pairs in array whose sum is divisible by K in C++
- Count pairs formed by distinct element sub-arrays in C++
- Count all subsequences having product less than K in C++
- Count subarrays whose product is divisible by k in C++
- Count of N-digit Numbers having Sum of even and odd positioned digits divisible by given numbers - JavaScript
- Count distinct pairs from two arrays having same sum of digits in C++
- Maximum OR sum of sub-arrays of two different arrays in C++
- Count pairs in array whose sum is divisible by 4 in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Maximize the size of array by deleting exactly k sub-arrays to make array prime in C++
- Find the longest sub-array having exactly k odd numbers in C++
- Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 in C++

Advertisements