Sunday, October 2, 2022
HomeSoftware DevelopmentRely distinct pair of indices in Array whose GCD and LCM are...

Rely distinct pair of indices in Array whose GCD and LCM are similar


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given an array A[] of size N, the duty is to seek out the entire variety of distinct pairs (i, j) of indices the place 1 ≤ i < j ≤ N such that the best frequent divisor(gcd) and least frequent a number of(lcm) of those parts are equal.

Examples:

Enter: A[] = {2, 5, 5, 5, 6} 
Output:

Rationalization: Right here pair (i, j) are: (2, 3), (3, 4), and (2, 4). 
To elaborate, gcd(A2, A3) = lcm(A2, A3) = 5.

Enter: A[] = {22, 22, 38, 38} 
Output: 2

Method: The issue will be solved primarily based on the next remark:

Observations:

  • The remark to be made right here is as follows: gcd(Ai, Aj) = lcm(Ai, Aj)⟺ Ai = Aj
  • So, the issue reduces to easily counting the variety of pairs of equal parts in A.
  • Construct a frequency map of the weather of A (utilizing map/unordered_map in C++, TreeMap/Hashmap in Java, or dict in python) after which iterate throughout its parts.
  • If a component x has a frequency of fx, then it contributes fx⋅(fx−1)/2 pairs to the reply, so sum this worth throughout all x.

Comply with the beneath steps to unravel the issue:

  • Declare a hash map.
  • Begin iterating over all the array
    • If the component is current within the map, then improve the worth of frequency by 1.
    • In any other case, insert that component into the map.
  • After that begin traversing the map and get the worth(frequency of component).
  • If a component x has a frequency of fx, then it contributes fx⋅(fx − 1) / 2 pairs to the reply, so sum this worth throughout all x.

Beneath is the implementation of the above strategy:

Java

import java.io.*;

import java.util.*;

  

public class GFG {

    

    

    public static lengthy pairCount(int a[], int n)

    {

        Map<Integer, Integer> mp = new HashMap<>();

        for (int i = 0; i < n; i++) {

            if (mp.containsKey(a[i])) {

                mp.put(a[i], mp.get(a[i]) + 1);

            }

            else {

                mp.put(a[i], 1);

            }

        }

        lengthy ans = 0;

        for (int i : mp.values()) {

            ans += (lengthy)i * (lengthy)(i - 1) / 2;

        }

        return ans;

    }

  

    

    public static void most important(String[] args)

    {

        int A[] = { 2, 5, 5, 5, 6 };

        int N = A.size;

  

        

        System.out.println(pairCount(A, N));

    }

}

Time Complexity: O(N) 
Auxiliary Area: O(1)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments