Find the maximum GCD of the siblings of a Binary Tree

06 Jun, 2022
Given a 2d-array arr[][] which represents the nodes of a Binary tree, the task is to find the maximum GCD of the siblings of this tree without actually constructing it.
Example:  
Input: arr[][] = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}} Output: 6 Explanation:  
For the above tree, the maximum GCD for the siblings is formed for the nodes 6 and 12 for the children of node 3.
Input: arr[][] = {{5, 4}, {5, 8}, {4, 6}, {4, 9}, {8, 10}, {10, 20}, {10, 30}} Output: 10  
Approach: The idea is to form a vector and store the tree in the form of the vector. After storing the tree in the form of a vector, the following cases occur: 
If the vector size is 0 or 1, then print 0 as GCD could not be found.
For all other cases, since we store the tree in the form of a pair, we consider the first values of two pairs and compare them. But first, you need to Sort the pair of edges.For example, let’s assume there are two pairs in the vector A and B. We check if:
A.first == B.first
If both of them match, then both of them belongs to the same parent. Therefore, we compute the GCD of the second values in the pairs and finally print the maximum of all such GCD’s.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to find the maximum// GCD of the siblings of a binary tree #include <bits/stdc++.h>using namespace std; // Function to find maximum GCDint max_gcd(vector<pair<int, int> >& v){    // No child or Single child    if (v.size() == 1 || v.size() == 0)        return 0;       sort(v.begin(), v.end());     // To get the first pair    pair<int, int> a = v[0];    pair<int, int> b;    int ans = INT_MIN;    for (int i = 1; i < v.size(); i++) {        b = v[i];         // If both the pairs belongs to        // the same parent        if (b.first == a.first)             // Update ans with the max            // of current gcd and            // gcd of both children            ans                = max(ans,                      __gcd(a.second,                            b.second));         // Update previous        // for next iteration        a = b;    }    return ans;} // Driver functionint main(){    vector<pair<int, int> > v;    v.push_back(make_pair(5, 4));    v.push_back(make_pair(5, 8));    v.push_back(make_pair(4, 6));    v.push_back(make_pair(4, 9));    v.push_back(make_pair(8, 10));    v.push_back(make_pair(10, 20));    v.push_back(make_pair(10, 30));     cout << max_gcd(v);    return 0;}
// Java program to find the maximum// GCD of the siblings of a binary treeimport java.util.*;import java.lang.*; class GFG{     // Function to find maximum GCDstatic int max_gcd(ArrayList<int[]> v){         // No child or Single child    if (v.size() == 1 || v.size() == 0)        return 0;         Collections.sort(v, new Comparator<int[]>() {        public int compare(int[] a, int[] b) {            return a[0]-b[0];        }    });       // To get the first pair    int[] a = v.get(0);    int[] b = new int[2];    int ans = Integer.MIN_VALUE;         for(int i = 1; i < v.size(); i++)    {        b = v.get(i);                 // If both the pairs belongs to        // the same parent        if (b[0] == a[0])               // Update ans with the max            // of current gcd and            // gcd of both children            ans = Math.max(ans,                           gcd(a[1],                               b[1]));               // Update previous        // for next iteration        a = b;    }    return ans;}  static int gcd(int a, int b){    if (b == 0)        return a;             return gcd(b, a % b);} // Driver codepublic static void main(String[] args){    ArrayList<int[]> v = new ArrayList<>();         v.add(new int[]{5, 4});    v.add(new int[]{5, 8});    v.add(new int[]{4, 6});    v.add(new int[]{4, 9});    v.add(new int[]{8, 10});    v.add(new int[]{10, 20});    v.add(new int[]{10, 30});         System.out.println(max_gcd(v));}} // This code is contributed by offbeat
# Python3 program to find the maximum# GCD of the siblings of a binary treefrom math import gcd # Function to find maximum GCDdef max_gcd(v):     # No child or Single child    if (len(v) == 1 or len(v) == 0):        return 0           v.sort()     # To get the first pair    a = v[0]    ans = -10**9    for i in range(1, len(v)):        b = v[i]         # If both the pairs belongs to        # the same parent        if (b[0] == a[0]):             # Update ans with the max            # of current gcd and            # gcd of both children            ans = max(ans, gcd(a[1], b[1]))         # Update previous        # for next iteration        a = b    return ans # Driver functionif __name__ == '__main__':    v=[]    v.append([5, 4])    v.append([5, 8])    v.append([4, 6])    v.append([4, 9])    v.append([8, 10])    v.append([10, 20])    v.append([10, 30])     print(max_gcd(v)) # This code is contributed by mohit kumar 29   
// C# program to find the maximum// GCD of the siblings of a binary treeusing System.Collections;using System; class GFG{      // Function to find maximum GCDstatic int max_gcd(ArrayList v){          // No child or Single child    if (v.Count == 1 || v.Count == 0)        return 0;       v.Sort();        // To get the first pair    int[] a = (int [])v[0];    int[] b = new int[2];    int ans = -10000000;          for(int i = 1; i < v.Count; i++)    {      b = (int[])v[i];             // If both the pairs belongs to      // the same parent      if (b[0] == a[0])                 // Update ans with the max        // of current gcd and        // gcd of both children        ans = Math.Max(ans, gcd(a[1], b[1]));             // Update previous      // for next iteration      a = b;    }    return ans;}   static int gcd(int a, int b){    if (b == 0)        return a;              return gcd(b, a % b);}  // Driver codepublic static void Main(string[] args){    ArrayList v = new ArrayList();          v.Add(new int[]{5, 4});    v.Add(new int[]{5, 8});    v.Add(new int[]{4, 6});    v.Add(new int[]{4, 9});    v.Add(new int[]{8, 10});    v.Add(new int[]{10, 20});    v.Add(new int[]{10, 30});          Console.Write(max_gcd(v));}} // This code is contributed by rutvik_56
<script> // JavaScript program to find the maximum// GCD of the siblings of a binary tree // Function to find maximum GCDfunction max_gcd(v){    // No child or Single child    if (v.length == 1 || v.length == 0)        return 0;     v.sort((a, b) => a - b);     // To get the first pair    let a = v[0];    let b;    let ans = Number.MIN_SAFE_INTEGER;    for (let i = 1; i < v.length; i++) {        b = v[i];         // If both the pairs belongs to        // the same parent        if (b[0] == a[0])             // Update ans with the max            // of current gcd and            // gcd of both children            ans                = Math.max(ans, gcd(a[1], b[1]));         // Update previous        // for next iteration        a = b;    }    return ans;} function gcd(a, b){    if (b == 0)        return a;              return gcd(b, a % b);}  // Driver function     let v = new Array();    v.push([5, 4]);    v.push([5, 8]);    v.push([4, 6]);    v.push([4, 9]);    v.push([8, 10]);    v.push([10, 20]);    v.push([10, 30]);     document.write(max_gcd(v));     // This code is contributed by gfgking     </script>
10
 
mohit kumar 29
offbeat
rutvik_56
snape_here
gfgking
vinayedula
Binary Tree
cpp-vector
GCD-LCM
HCF
Arrays
Tree
Arrays
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.