Open In App

Count pairs in array whose sum is divisible by 4

Improve
Improve
Like Article
Like
Save
Share
Report

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: 3
Explanation:
Only three pairs are possible whose sum
is divisible by '4' i.e., (2, 2),
(1, 7) and (7, 5)
Input: {2, 2, 3, 5, 6}
Output: 4

Brute Force Approach:

The brute force approach to solve this problem would be to use two nested loops to iterate over all possible pairs of integers in the array and check if their sum is divisible by 4. If so, increment a counter variable.

  • Initialize a variable ‘count’ to 0 to keep track of the number of pairs whose sum is divisible by 4.
  • Traverse through all pairs of elements in the array using two nested loops.
  • For each pair, calculate the sum of the two elements.
  • Check if the sum is divisible by 4 using the modulo operator (%).
  • If the sum is divisible by 4, increment the count by 1.
  • After checking all pairs, return the count.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <vector>
 
using namespace std;
 
int countPairsDivisibleBy4(vector<int>& arr) {
    int count = 0;
    int n = arr.size();
 
    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n; j++) {
            if((arr[i] + arr[j]) % 4 == 0) {
                count++;
            }
        }
    }
 
    return count;
}
 
int main() {
    vector<int> arr1 = {2, 2, 1, 7, 5};
    vector<int> arr2 = {2, 2, 3, 5, 6};
     
    cout << countPairsDivisibleBy4(arr1) << endl; // Output: 3
    cout << countPairsDivisibleBy4(arr2) << endl; // Output: 4
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
class GFG {
   
      // This function counts the number of pairs whose
   // sum is divisible by 4
    public static int countPairsDivisibleBy4(List<Integer> arr) {
        int count = 0;
        int n = arr.size();
         
          // Iterating over each pair
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((arr.get(i) + arr.get(j)) % 4 == 0) {
                    count++;
                }
            }
        }
 
        return count;
    }
     
      // Driver code
    public static void main(String[] args) {
        List<Integer> arr1 = new ArrayList<>(List.of(2, 2, 1, 7, 5));
        List<Integer> arr2 = new ArrayList<>(List.of(2, 2, 3, 5, 6));
 
          // Function call
        System.out.println(countPairsDivisibleBy4(arr1)); // Output: 3
        System.out.println(countPairsDivisibleBy4(arr2)); // Output: 4
    }
}


Python3




def countPairsDivisibleBy4(arr):
    count = 0
    n = len(arr)
 
    # Iterating over each pair
    for i in range(n):
        for j in range(i + 1, n):
            if (arr[i] + arr[j]) % 4 == 0:
                count += 1
 
    return count
 
 
# Driver code
if __name__ == '__main__':
    arr1 = [2, 2, 1, 7, 5]
    arr2 = [2, 2, 3, 5, 6]
 
    # Function call
    print(countPairsDivisibleBy4(arr1))  # Output: 3
    print(countPairsDivisibleBy4(arr2))  # Output: 4
 
# This code is contributed by akshitaguprzj3


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    // This function counts the number of pairs whose
    // sum is divisible by 4
    public static int CountPairsDivisibleBy4(List<int> arr)
    {
        int count = 0;
        int n = arr.Count;
 
        // Iterating over each pair
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                if ((arr[i] + arr[j]) % 4 == 0)
                {
                    count++;
                }
            }
        }
 
        return count;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        List<int> arr1 = new List<int>(new int[] { 2, 2, 1, 7, 5 });
        List<int> arr2 = new List<int>(new int[] { 2, 2, 3, 5, 6 });
 
        // Function call
        Console.WriteLine(CountPairsDivisibleBy4(arr1)); // Output: 3
        Console.WriteLine(CountPairsDivisibleBy4(arr2)); // Output: 4
    }
}
 
// by phasing17


Javascript




function countPairsDivisibleBy4(arr) {
    let count = 0;
    const n = arr.length;
 
    // Iterating over each pair
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            if ((arr[i] + arr[j]) % 4 === 0) {
                count++;
            }
        }
    }
 
    return count;
}
 
// Driver code
const arr1 = [2, 2, 1, 7, 5];
const arr2 = [2, 2, 3, 5, 6];
 
// Function call
console.log(countPairsDivisibleBy4(arr1)); // Output: 3
console.log(countPairsDivisibleBy4(arr2)); // Output: 4
 
// This code is contributed by akshitaguprzj3


Output

3
4








Time Complexity: O(n^2), where n is the size input array. 

Auxiliary Space: O(1), as we are not using any extra space.

Efficient approach is to use Hashing technique. There are only three condition that can arise whose sum is divisible by ‘4’ i.e,

  1. If both are divisible by 4.
  2. If one of them is equal to 1 modulo 4 and other is 3 modulo 4. For instance, (1, 3), (5, 7), (5, 11).
  3. If both of them is equal to 2 modulo 4 i.e., (2, 2), (2, 6), (6, 10)

Store all modulo in freq[] array such that freq[i] = number of array elements that are equal to
i modulo 4

Thus answer =>
 

Implementation:

C++




// C++ Program to count pairs
// whose sum divisible by '4'
#include <bits/stdc++.h>
using namespace std;
 
// Program to count pairs whose sum divisible
// by '4'
int count4Divisibiles(int arr[], int n)
{
    // Create a frequency array to count
    // occurrences of all remainders when
    // divided by 4
    int freq[4] = {0, 0, 0, 0};
 
    // Count occurrences of all remainders
    for (int i = 0; i < n; i++)
        ++freq[arr[i] % 4];
 
    // If both pairs are divisible by '4'
    int ans = freq[0] * (freq[0] - 1) / 2;
 
    // If both pairs are 2 modulo 4
    ans += freq[2] * (freq[2] - 1) / 2;
 
    // If one of them is equal
    // to 1 modulo 4 and the
    // other is equal to 3
    // modulo 4
    ans += freq[1] * freq[3];
 
    return ans;
}
 
// Driver code
int main()
{
 
    int arr[] = { 2, 2, 1, 7, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << count4Divisibiles(arr, n);
 
    return 0;
}


Java




// Java program to count pairs
// whose sum divisible by '4'
import java.util.*;
 
class Count{
    public static int count4Divisibiles(int arr[] ,
                                            int n )
    {
        // Create a frequency array to count
        // occurrences of all remainders when
        // divided by 4
        int freq[] = {0, 0, 0, 0};
        int i = 0;
        int ans;
         
        // Count occurrences of all remainders
        for (i = 0; i < n; i++)
                ++freq[arr[i] % 4];
         
        //If both pairs are divisible by '4'
        ans = freq[0] * (freq[0] - 1) / 2;
     
        // If both pairs are 2 modulo 4
        ans += freq[2] * (freq[2] - 1) / 2;
     
        // If one of them is equal
        // to 1 modulo 4 and the
        // other is equal to 3
        // modulo 4
        ans += freq[1] * freq[3];
     
        return (ans);
    }
    public static void main(String[] args)
    {
        int arr[] = {2, 2, 1, 7, 5};
        int n = 5;
        System.out.print(count4Divisibiles(arr, n));
    }
}
 
// This code is contributed by rishabh_jain


Python3




# Python3 code to count pairs whose
# sum is divisible by '4'
 
# Function to count pairs whose
# sum is divisible by '4'
def count4Divisibiles( arr , n ):
     
    # Create a frequency array to count
    # occurrences of all remainders when
    # divided by 4
    freq = [0, 0, 0, 0]
     
    # Count occurrences of all remainders
    for i in range(n):
        freq[arr[i] % 4]+=1
         
    #If both pairs are divisible by '4'
    ans = freq[0] * (freq[0] - 1) / 2
     
    # If both pairs are 2 modulo 4
    ans += freq[2] * (freq[2] - 1) / 2
     
    # If one of them is equal
    # to 1 modulo 4 and the
    # other is equal to 3
    # modulo 4
    ans += freq[1] * freq[3]
     
    return int(ans)
 
# Driver code
arr = [2, 2, 1, 7, 5]
n = len(arr)
print(count4Divisibiles(arr, n))
 
# This code is contributed by "Sharad_Bhardwaj".


C#




// C# program to count pairs
// whose sum divisible by '4'
using System;
 
class Count{
    public static int count4Divisibiles(int []arr ,
                                            int n )
    {
        // Create a frequency array to count
        // occurrences of all remainders when
        // divided by 4
        int []freq = {0, 0, 0, 0};
        int i = 0;
        int ans;
         
        // Count occurrences of all remainders
        for (i = 0; i < n; i++)
            ++freq[arr[i] % 4];
         
        //If both pairs are divisible by '4'
        ans = freq[0] * (freq[0] - 1) / 2;
     
        // If both pairs are 2 modulo 4
        ans += freq[2] * (freq[2] - 1) / 2;
     
        // If one of them is equal
        // to 1 modulo 4 and the
        // other is equal to 3
        // modulo 4
        ans += freq[1] * freq[3];
     
        return (ans);
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = {2, 2, 1, 7, 5};
        int n = 5;
        Console.WriteLine(count4Divisibiles(arr, n));
    }
}
 
// This code is contributed by vt_m


Javascript




// JavaScript Program to count pairs
// whose sum divisible by '4'
 
// Program to count pairs whose sum divisible
// by '4'
function count4Divisibiles(arr, n)
{
    // Create a frequency array to count
    // occurrences of all remainders when
    // divided by 4
    let freq = [0, 0, 0, 0];
 
    // Count occurrences of all remainders
    for (var i = 0; i < n; i++)
        ++freq[arr[i] % 4];
 
    // If both pairs are divisible by '4'
    let ans = Math.floor(freq[0] * (freq[0] - 1) / 2);
 
    // If both pairs are 2 modulo 4
    ans += Math.floor(freq[2] * (freq[2] - 1) / 2);
 
    // If one of them is equal
    // to 1 modulo 4 and the
    // other is equal to 3
    // modulo 4
    ans += freq[1] * freq[3];
 
    return ans;
}
 
// Driver code
let arr = [ 2, 2, 1, 7, 5 ];
let n = arr.length;
 
console.log(count4Divisibiles(arr, n));
 
 
 
// This code is contributed by phasing17


PHP




<?php
// PHP Program to count pairs
// whose sum divisible by '4'
 
// Program to count pairs whose
// sum divisible by '4'
function count4Divisibiles($arr, $n)
{
    // Create a frequency array to
    // count occurrences of all
    // remainders when divided by 4
    $freq = array(0, 0, 0, 0);
 
    // Count occurrences
    // of all remainders
    for ( $i = 0; $i < $n; $i++)
        ++$freq[$arr[$i] % 4];
 
    // If both pairs are
    // divisible by '4'
    $ans = $freq[0] *
        ($freq[0] - 1) / 2;
 
    // If both pairs are
    // 2 modulo 4
    $ans += $freq[2] *
        ($freq[2] - 1) / 2;
 
    // If one of them is equal
    // to 1 modulo 4 and the
    // other is equal to 3
    // modulo 4
    $ans += $freq[1] * $freq[3];
 
    return $ans;
}
 
// Driver code
$arr = array(2, 2, 1, 7, 5);
$n = sizeof($arr) ;
 
echo count4Divisibiles($arr, $n);
 
// This code is contributed by ajit
?>


Output

3







Time complexity: O(n)
Auxiliary space: O(1)



Last Updated : 24 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads