VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-original-numbers-from-gcd-every-pair/

⇱ Find original numbers from gcd() every pair - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find original numbers from gcd() every pair

Last Updated : 11 Jul, 2025

Given an array arr[] containing GCD of every possible pair of elements of another array. The task is to find the original numbers which are used to calculate the GCD array. For example, if original numbers are {4, 6, 8} then the given array will be {4, 2, 4, 2, 6, 2, 4, 2, 8}. 

👁 Image


Examples: 

Input: arr[] = {5, 1, 1, 12} 
Output: 12 5 
gcd(12, 12) = 12 
gcd(12, 5) = 1 
gcd(5, 12) = 1 
gcd(5, 5) = 5

Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2} 
Output: 12 10 7 5 1 
 

Approach: 

  1. Sort the array in decreasing order.
  2. Highest element will always be one of the original numbers. Keep that number and remove it from the array.
  3. Compute GCD of the element taken in the previous step with the current element starting from the greatest and discard the GCD value from the given array.

Below is the implementation of the above approach: 


Output: 
12 10 7 5 1

 

Time Complexity: O(n2)
Auxiliary Space: O(?n+k) where n is the size of array and k is the maximum element of the array.

Comment
Article Tags: