Sort an array in increasing order of GCD of their digits

Given an array arr[] consisting of N positive integers, the task is to sort the array arr[] according to the increasing order of GCD of digits of each element. If GCD of two or more elements are the same then, sort according to their values.
Examples:
Input: arr[] = {555, 363, 488, 244}
Output: 244 363 488 555
Explanation:
Following the GCD of the digits of each number:
- 555: GCD(5, 5, 5) = 5.
- 363: GCD(3, 6, 3) = 3.
- 488: GCD(4, 8, 8) = 4.
- 244: GCD(2, 4, 4) = 2.
After sorting according the given criteria, the order of elements are {244, 363, 488, 555}.
Input: arr[] = {555, 363, 488, 244, 444, 5}
Output: 244 363 444 488 5 555
Approach: The given problem can be solved by using the comparator function with the sort() function. The comparator function is defined as:
- It takes two arguments at a time and returns true if the GCD of the first argument is less than the second argument.
- If the GCD value is the same, then it returns true if the first argument is less than the second argument. Otherwise, return false.
Below is the implementation of the above approach:
C++
// C++ program for above approach#include<bits/stdc++.h>using namespace std;Â
// Function to calculate GCD of two integersint gcd(int a, int b){         // Base case    if (b == 0)        return a;              // Recursively calculate GCD    return gcd(b, a % b);}  // Function to calculate GCD of// digits of array elementsint keyFunc(int n){    int getGCD = 0;          while (n > 0)    {        getGCD = gcd(n % 10, getGCD);          // If at point GCD becomes 1,        // return it        if (getGCD == 1)            return 1;          n = n / 10;    }    return getGCD;}Â
// Comparator function that compares // elements according to their gcd value.bool compare(int o1, int o2){    int x = keyFunc(o1);    int y = keyFunc(o2);         if(x == y)    {        return o1 < o2;     }    return x < y;} Â
// Function to sort an array in according// to GCD of digits of array elementsvoid sortArrayByGCD(vector<int>arr){    vector<int>list;    for(int i : arr)    {        list.push_back(i);    }          // Sort the array according to gcd of    // digits using comparator function    sort(list.begin(), list.end(), compare);         // Print the resultant array    for(int i : list)    {        cout << i << " ";    }}  // Driver codeint main(){    vector<int>arr = { 555, 363, 488, 244 };;    sortArrayByGCD(arr);}Â
// This code is contributed by nirajgusain5 |
Java
// Java program for the above approachimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator;Â
class GFG{     // Function to calculate GCD of two integersstatic int gcd(int a, int b){         // Base case    if (b == 0)        return a;             // Recursively calculate GCD    return gcd(b, a % b);}Â
// Function to calculate GCD of // digits of array elementsstatic int keyFunc(int n){Â Â Â Â int getGCD = 0;Â Â Â Â Â Â Â Â Â while (n > 0) Â Â Â Â {Â Â Â Â Â Â Â Â getGCD = gcd(n % 10, getGCD);Â
        // If at point GCD becomes 1,        // return it        if (getGCD == 1)            return 1;Â
        n = n / 10;    }    return getGCD;}Â
// Function to sort an array in according // to GCD of digits of array elementspublic static void sortArrayByGCD(int[] arr){    ArrayList<Integer> list = new ArrayList<Integer>();    for(int i : arr)     {        list.add(i);    }         // Sort the array according to gcd of    // digits using comparator function    Collections.sort(list, new Comparator<Integer>()    {        @Override        public int compare(Integer o1, Integer o2)        {            int x = keyFunc(o1) - keyFunc(o2);            if (x == 0)            {                if (o1 > o2)                    x = 1;                else                    x = -1;            }            return x;        }    });         // Print the resultant array    for(int i : list)    {        System.out.print(i + " ");    }}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int arr[] = { 555, 363, 488, 244 };Â Â Â Â sortArrayByGCD(arr);}}Â
// This code is contributed by abhinavjain194 |
Python3
# Python3 program for the above approachÂ
# Function to calculate# GCD of two integersdef gcd(a, b):       # Base Case    if not b:        return a           # Recursively calculate GCD    return gcd(b, a % b)Â
# Function to calculate GCD# of two array elementsdef keyFunc(n):Â Â Â Â getGCD = int(str(n)[0])Â Â Â Â Â Â Â Â Â # Update the getGCDÂ Â Â Â for i in str(n):Â Â Â Â Â Â Â Â getGCD = gcd(getGCD, int(i))Â Â Â Â Â Â Â Â Â Â Â Â Â # Return the resultant GCDÂ Â Â Â return getGCDÂ
# Function to sort an array by# increasing order of GCD of# digits of array elementsdef sortArrayByGCD(arr):Â
    # Sort the array    arr.sort()Â
    # Sort the array according to gcd of    # digits using comparator function    arr = sorted(arr, key = keyFunc)Â
    # Print the resultant array    print(*arr)Â
# Driver Code     # Given arrayarr = [555, 363, 488, 244]sortArrayByGCD(arr) |
C#
using System;using System.Linq;Â
class GFG{Â Â static int Gcd(int a, int b)Â Â {Â Â Â Â if (b == 0)Â Â Â Â Â Â return a;Â Â Â Â return Gcd(b, a % b);Â Â }Â
  static int KeyFunc(int n)  {    int gcd = 0;    while (n > 0)    {      gcd = Gcd(n % 10, gcd);      if (gcd == 1)        return 1;      n /= 10;    }    return gcd;  }Â
  static void SortArrayByGcd(int[] arr)  {    var list = arr.ToList();    list.Sort((o1, o2) =>              {                var x = KeyFunc(o1) - KeyFunc(o2);                if (x == 0)                {                  if (o1 > o2)                    x = 1;                  else                    x = -1;                }                return x;              });    Console.WriteLine(string.Join(" ", list));  }Â
  static void Main(string[] args)  {    int[] arr = { 555, 363, 488, 244 };    SortArrayByGcd(arr);  }}Â
// This code is contributed by aadityaburujwale. |
Javascript
<script>Â
// JavaScript program for above approachÂ
// Function to calculate GCD of two integersfunction gcd(a, b) {Â
    // Base case    if (b == 0)        return a;Â
    // Recursively calculate GCD    return gcd(b, a % b);}Â
Â
// Function to calculate GCD of// digits of array elementsfunction keyFunc(n) {Â Â Â Â let getGCD = String(n)[0]Â
    // Update the getGCD    for (let i = 0; i < n; i++)        getGCD = gcd(getGCD, i)Â
    // Return the resultant GCD    return getGCD}Â
Â
// Function to sort an array in according// to GCD of digits of array elementsfunction sortArrayByGCD(arr) {    // Sort the array    arr.sort()Â
    // Sort the array according to gcd of    // digits using comparator function    arr = arr.sort(keyFunc)Â
    // Print the resultant array    for (let i of arr) {        document.write(i + " ")    }}Â
// Driver codelet arr = [555, 363, 488, 244];sortArrayByGCD(arr);Â
</script> |
244 363 488 555
Â
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



