Skip to content
Related Articles

Related Articles

Sort an array in increasing order of GCD of their digits
  • Last Updated : 19 Apr, 2021

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:

  1. 555: GCD(5, 5, 5) = 5.
  2. 363: GCD(3, 6, 3) = 3.
  3. 488: GCD(4, 8, 8) = 4.
  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:

Python3




# Python program for the above approach
  
# Function to calculate
# GCD of two integers
def 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 elements
def 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 elements
def 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 array
arr = [555, 363, 488, 244]
sortArrayByGCD(arr)
Output:
244 363 488 555

Time Complexity: O(N * log N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :