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: 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

Naive approach is to iterate through every pair of array bu using two nested for loops and count those pairs whose sum is divisible by ‘4’. Time complexity of this approach is O(n2).

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 =>
    \implies \displaystyle {{freq[0]} \choose 2} + {freq[2] \choose 2} + freq[1] \cdot freq[3]
    
    \implies \displaystyle \frac{freq_0 (freq_0-1)}{2} +\frac{freq_2 (freq_2-1)}{2} +         freq_1 \cdot freq_3 
    
    

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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;
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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

    chevron_right

    
    

    Python3

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # 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".

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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

    chevron_right

    
    

    PHP

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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
    ?>

    chevron_right

    
    


    Output :

     3
    

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



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



    Improved By : jit_t



    Article Tags :
    Practice Tags :


    5


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.