Pair sum divisible by K in java

Pair sum divisible by K in java

Given an array of N integers and an integer K, your task is to calculate the count of pairs whose sum is divisible by K.

Input Format:

The first line of input contains two integers N and K.

The next line contains N space-separated integers depicting values of an array.

Output Format:

Print the count of required pairs.

Example 1

Input

5 4 
1 2 3 4 5

Output

2

Explanation

Here , 2 pairs are possible whose sum is divisible by 3 i.e (1 3) and (3 5) are the required pairs

Example 2

Input

5 3 
1 2 3 4 5

Output

4

Explanation

Here , 4 pairs are possible whose sum is divisible by 3 i.e (1 5), (1 2), (2 4), and (4 5) are the required pairs.

Constraints:

1 < = N < = 10^5

1 < = A[i] <= 10^5

1 <= K <= 10^5

Solution:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int N = sc.nextInt();
      int K = sc.nextInt();

      int arr[] = new int[N];
      int count=0;
      
      for(int i=0;i<N;i++)
        {
          arr[i]=sc.nextInt();
        }

      for(int i=0;i<N;i++)
        {
          for(int j=i+1;j<N;j++)
            {
                if((arr[i]+arr[j])%K==0)
                {
                  count++;
                }
            }
        }
      System.out.println(count);
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *