Divisible Sum Pairs in java

Divisible Sum Pairs in java

Given an array of integers and a positive integer k, determine the number of (i,j) pairs in the array where i<j and arr[i] + arr[j] is divisible by k.

Example

arr = [1, 2, 3, 4, 5, 6] k = 5 Three pairs meet the criteria: [1, 4], [2, 3] and [4, 6].

Input Format

The first line contains 2 space-separated integers, n and k.
The second line contains n space-separated integers, each a value of arr[i].

Sample Input

6 3          
1 3 2 6 1 2  

Sample Output

5

Explanation

Here are the 5 valid pairs when k = 3:

(0,2) = arr[0]+arr[2] = 1 + 2 = 3

(0,5) = arr[0]+arr[5] = 1+ 2 = 3

(1,3) = arr[1]+arr[3] = 3 + 6 = 9

(2,4) = arr[2]+arr[4] = 2 + 1 = 3

(4,5) = arr[4]+arr[5] = 1 + 2 = 3

Solution of Divisible Sum Pairs in java:–

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 scanner = new Scanner(System.in);
      int n = scanner.nextInt();
      int k = scanner.nextInt();
      
      int arr[] = new int[n];
      int count=0;

      for(int i=0;i<n;i++)
        {
          int value =scanner.nextInt();
          arr[i]=value;
        }

      

      for(int i=0;i<n;i++)
        {
          for(int j=0;j<n;j++)
            {
              if((arr[i]+arr[j])%k==0 && i<j)
              {
                count++;
              }
            }
        }
      System.out.println(count);
	}
}

Add a Comment

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