Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Count pairs in array whose sum is divisible by K
Next article icon

Count pairs in array whose sum is divisible by K

Last Updated : 25 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K. 
Note: This question is a generalized version of this 


Examples: 

Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 Explanation :  There are five pairs possible whose sum is divisible by '4' i.e., (2, 2),  (1, 7), (7, 5), (1, 3) and (5, 3)  Input : A[] = {5, 9, 36, 74, 52, 31, 42}, K = 3 Output : 7
Recommended Practice
Count pairs in array divisible by K
Try It!

Naive Approach: The simplest approach is to iterate through every pair of the array but using two nested for loops and count those pairs whose sum is divisible by 'K'. The time complexity of this approach is O(N2).

 Below is the implementation of the above approach:

C++
// C++ Program to count pairs // whose sum divisible by 'K' #include <bits/stdc++.h> using namespace std;  int countKdivPairs(int A[], int n, int K) {     // variable for storing answer     int count = 0;      for (int i = 0; i < n; i++) {         for (int j = i + 1; j < n; j++) {              // if pair sum is divisible             if ((A[i] + A[j]) % K == 0)                  // Increment count                 count++;         }     }      return count; }  // Driver code int main() {      int A[] = { 2, 2, 1, 7, 5, 3 };     int n = sizeof(A) / sizeof(A[0]);     int K = 4;      // Function call     cout << countKdivPairs(A, n, K);      return 0; } 
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG {    static int countKdivPairs(int[] A, int n, int K)   {      // variable for storing answer     int count = 0;      for (int i = 0; i < n; i++) {       for (int j = i + 1; j < n; j++) {          // if pair sum is divisible         if ((A[i] + A[j]) % K == 0)            // Increment count           count++;       }     }      return count;   }    public static void main (String[] args)    {     int[] A = { 2, 2, 1, 7, 5, 3 };     int n = A.length;     int K = 4;      // Function call     System.out.println(countKdivPairs(A, n, K));   } }  // This code is contributed by utkarshshirode02 
C#
// C# Program to count pairs // whose sum divisible by 'K' using System; class GFG {    static int countKdivPairs(int[] A, int n, int K)   {          // variable for storing answer     int count = 0;      for (int i = 0; i < n; i++) {       for (int j = i + 1; j < n; j++) {          // if pair sum is divisible         if ((A[i] + A[j]) % K == 0)            // Increment count           count++;       }     }      return count;   }    // Driver code   public static void Main()   {      int[] A = { 2, 2, 1, 7, 5, 3 };     int n = A.Length;     int K = 4;      // Function call     Console.Write(countKdivPairs(A, n, K));   } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
// Javascript Program to count pairs // whose sum divisible by 'K'  function countKdivPairs(A, n, K) {     // variable for storing answer     let count = 0      for (let i = 0; i < n; i++) {         for (let j = i + 1; j < n; j++) {              // if pair sum is divisible             if ((A[i] + A[j]) % K == 0)                  // Increment count                 count++         }     }      return count }  // Driver code let A = [ 2, 2, 1, 7, 5, 3 ] let n = A.length let K = 4  // Function call console.log(countKdivPairs(A, n, K))  // This code is contributed by Samim Hossain Mondal. 
Python3
# Python Program to count pairs # whose sum divisible by 'K' def countKdivPairs(A, n, K):     count = 0     for i in range(0, n):         for j in range(i+1, n):             if((A[i]+A[j]) % K==0):                 # Increment count                 count += 1     return count # Driver Code  A=[ 2, 2, 1, 7, 5, 3 ] n = len(A) K = 4 #Function call print(countKdivPairs(A, n, K))        

Output
5

Time complexity: O(N2), for using two nested loops.
Auxiliary Space: O(1), as constant space is used.

Efficient Approach: An efficient approach is to use Hashing technique. We will separate elements into buckets depending on their (value mod K). When a number is divided by K then the remainder may be 0, 1, 2, up to (k-1). So take an array to say freq[] of size K (initialized with Zero) and increase the value of freq[A[i]%K] so that we can calculate the number of values giving remainder j on division with K.

C++
// C++ Program to count pairs // whose sum divisible by 'K' #include <bits/stdc++.h> using namespace std;  // Program to count pairs whose sum divisible // by 'K' int countKdivPairs(int A[], int n, int K) {     // Create a frequency array to count     // occurrences of all remainders when     // divided by K     int freq[K] = { 0 };      // Count occurrences of all remainders     for (int i = 0; i < n; i++)         ++freq[A[i] % K];      // If both pairs are divisible by 'K'     int sum = freq[0] * (freq[0] - 1) / 2;      // count for all i and (k-i)     // freq pairs     for (int i = 1; i <= K / 2 && i != (K - i); i++)         sum += freq[i] * freq[K - i];     // If K is even     if (K % 2 == 0)         sum += (freq[K / 2] * (freq[K / 2] - 1) / 2);     return sum; }  // Driver code int main() {      int A[] = { 2, 2, 1, 7, 5, 3 };     int n = sizeof(A) / sizeof(A[0]);     int K = 4;     cout << countKdivPairs(A, n, K);      return 0; } 
Java
// Java program to count pairs // whose sum divisible by 'K' import java.util.*;  class Count {     public static int countKdivPairs(int A[], int n, int K)     {         // Create a frequency array to count         // occurrences of all remainders when         // divided by K         int freq[] = new int[K];          // Count occurrences of all remainders         for (int i = 0; i < n; i++)             ++freq[A[i] % K];          // If both pairs are divisible by 'K'         int sum = freq[0] * (freq[0] - 1) / 2;          // count for all i and (k-i)         // freq pairs         for (int i = 1; i <= K / 2 && i != (K - i); i++)             sum += freq[i] * freq[K - i];         // If K is even         if (K % 2 == 0)             sum += (freq[K / 2] * (freq[K / 2] - 1) / 2);         return sum;     }     public static void main(String[] args)     {         int A[] = { 2, 2, 1, 7, 5, 3 };         int n = 6;         int K = 4;         System.out.print(countKdivPairs(A, n, K));     } } 
Python3
# Python3 code to count pairs whose  # sum is divisible by 'K'  # Function to count pairs whose  # sum is divisible by 'K' def countKdivPairs(A, n, K):          # Create a frequency array to count      # occurrences of all remainders when      # divided by K     freq = [0] * K          # Count occurrences of all remainders     for i in range(n):         freq[A[i] % K]+= 1              # If both pairs are divisible by 'K'     sum = freq[0] * (freq[0] - 1) / 2;          # count for all i and (k-i)     # freq pairs     i = 1     while(i <= K//2 and i != (K - i) ):         sum += freq[i] * freq[K-i]         i+= 1      # If K is even     if( K % 2 == 0 ):         sum += (freq[K//2] * (freq[K//2]-1)/2);          return int(sum)  # Driver code A = [2, 2, 1, 7, 5, 3] n = len(A) K = 4 print(countKdivPairs(A, n, K)) 
C#
// C# program to count pairs // whose sum divisible by 'K' using System;  class Count {     public static int countKdivPairs(int []A, int n, int K)     {         // Create a frequency array to count         // occurrences of all remainders when         // divided by K         int []freq = new int[K];          // Count occurrences of all remainders         for (int i = 0; i < n; i++)             ++freq[A[i] % K];          // If both pairs are divisible by 'K'         int sum = freq[0] * (freq[0] - 1) / 2;          // count for all i and (k-i)         // freq pairs         for (int i = 1; i <= K / 2 && i != (K - i); i++)             sum += freq[i] * freq[K - i];                      // If K is even         if (K % 2 == 0)             sum += (freq[K / 2] * (freq[K / 2] - 1) / 2);         return sum;     }          // Driver code     static public void Main ()     {         int []A = { 2, 2, 1, 7, 5, 3 };         int n = 6;         int K = 4;         Console.WriteLine(countKdivPairs(A, n, K));     } }  // This code is contributed by akt_mit. 
PHP
<?php // PHP Program to count pairs // whose sum divisible by 'K'  // Program to count pairs whose sum  // divisible by 'K' function countKdivPairs($A, $n, $K) {          // Create a frequency array to count     // occurrences of all remainders when     // divided by K     $freq = array_fill(0, $K, 0);      // Count occurrences of all remainders     for ($i = 0; $i < $n; $i++)         ++$freq[$A[$i] % $K];      // If both pairs are divisible by 'K'     $sum = (int)($freq[0] * ($freq[0] - 1) / 2);      // count for all i and (k-i)     // freq pairs     for ($i = 1; $i <= $K / 2 &&                   $i != ($K - $i); $i++)         $sum += $freq[$i] * $freq[$K - $i];              // If K is even     if ($K % 2 == 0)         $sum += (int)($freq[(int)($K / 2)] *                       ($freq[(int)($K / 2)] - 1) / 2);     return $sum; }  // Driver code $A = array( 2, 2, 1, 7, 5, 3 ); $n = count($A); $K = 4; echo countKdivPairs($A, $n, $K);  // This code is contributed by mits ?> 
JavaScript
<script>     // Javascript program to count pairs whose sum divisible by 'K'          function countKdivPairs(A, n, K)     {         // Create a frequency array to count         // occurrences of all remainders when         // divided by K         let freq = new Array(K);         freq.fill(0);           // Count occurrences of all remainders         for (let i = 0; i < n; i++)             ++freq[A[i] % K];           // If both pairs are divisible by 'K'         let sum = freq[0] * parseInt((freq[0] - 1) / 2, 10);           // count for all i and (k-i)         // freq pairs         for (let i = 1; i <= K / 2 && i != (K - i); i++)             sum += freq[i] * freq[K - i];                       // If K is even         if (K % 2 == 0)             sum += parseInt(freq[parseInt(K / 2, 10)] * (freq[parseInt(K / 2, 10)] - 1) / 2, 10);         return sum;     }          let A = [ 2, 2, 1, 7, 5, 3 ];     let n = 6;     let K = 4;     document.write(countKdivPairs(A, n, K));          </script> 

Output
5

Time complexity: O(N) 
Auxiliary space: O(K), since K extra space has been taken.

https://www.youtube.com/watch?v=5UJvXcSUyT0


Next Article
Count pairs in array whose sum is divisible by K

C

Chandan_Agrawal
Improve
Article Tags :
  • Algorithms
  • Mathematical
  • Technical Scripter
  • Python
  • DSA
  • Arrays
  • subarray
  • Arrays
  • Hash
  • Marketing
Practice Tags :
  • Algorithms
  • Arrays
  • Arrays
  • Hash
  • Mathematical
  • python

Similar Reads

    Count pairs in array whose sum is divisible by 4
    Given a array if 'n' positive integers. Count number of pairs of integers in the array that have the sum divisible by 4. Examples : Input: {2, 2, 1, 7, 5}Output: 3Explanation:Only three pairs are possible whose sumis divisible by '4' i.e., (2, 2), (1, 7) and (7, 5)Input: {2, 2, 3, 5, 6}Output: 4Reco
    9 min read
    Count pairs in Array whose product is divisible by K
    Given a array vec and an integer K, count the number of pairs (i, j) such that vec[i]*vec[j] is divisible by K where i<j. Examples: Input: vec = {1, 2, 3, 4, 5, 6}, K = 4Output: 6Explanation: The pairs of indices (0, 3), (1, 3), (2, 3), (3, 4), (3, 5) and (1, 5) satisfy the condition as their pro
    11 min read
    Count of pairs in Array whose product is divisible by K
    Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose product is divisible by K. Examples : Input: A[] = [1, 2, 3, 4, 5], K = 2Output: 7Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are(0, 1), (0, 3), (1, 2)
    9 min read
    Count sub-arrays whose product is divisible by k
    Given an integer K and an array arr[], the task is to count all the sub-arrays whose product is divisible by K.Examples: Input: arr[] = {6, 2, 8}, K = 4 Output: 4 Required sub-arrays are {6, 2}, {6, 2, 8}, {2, 8}and {8}.Input: arr[] = {9, 1, 14}, K = 6 Output: 1 Naive approach: Run nested loops and
    15+ min read
    Check If Array Pair Sums Divisible by k
    Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k.Examples: Input: arr[] = [9, 7, 5, 3], k = 6 Output: True We can divide the array into (9, 3) and (7, 5). Sum of both of these
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences