- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Find original numbers from gcd() every pair in Python

Suppose we have an array A where GCD of every possible pair of elements of another array is given, we have to find the original numbers which are used to compute the given GCD array.

So, if the input is like A = [6, 1, 1, 13], then the output will be [13, 6] as gcd(13, 13) is 13, gcd(13, 6) is 1, gcd(6, 13) is 1, gcd(6, 6) is 6

To solve this, we will follow these steps −

n := size of A

sort array A in descending order

occurrence := an array of size A[0] and fill with 0

for i in range 0 to n, do

occurrence[A[i]] := occurrence[A[i]] + 1

size := integer of square root of n

res := an array of size same as size of A and fill with 0

l := 0

for i in range 0 to n, do

if occurrence[A[i]] > 0, then

res[l] := A[i]

occurrence[res[l]] := occurrence[res[l]] - 1

l := l + 1

for j in range 0 to l, do

if i is not same as j, then

g := gcd(A[i], res[j])

occurrence[g] := occurrence[g] - 2

return res[from index 0 to size]

## Example

Let us see the following implementation to get better understanding −

from math import sqrt, gcd def get_actual_array(A): n = len(A) A.sort(reverse = True) occurrence = [0 for i in range(A[0] + 1)] for i in range(n): occurrence[A[i]] += 1 size = int(sqrt(n)) res = [0 for i in range(len(A))] l = 0 for i in range(n): if (occurrence[A[i]] > 0): res[l] = A[i] occurrence[res[l]] -= 1 l += 1 for j in range(l): if (i != j): g = gcd(A[i], res[j]) occurrence[g] -= 2 return res[:size] A = [6, 1, 1, 13] print(get_actual_array(A))

## Input

[6, 1, 1, 13]

## Output

[13, 6]

- Related Articles
- Find original numbers from gcd() every pair in C++
- Print N lines of numbers such that every pair among numbers has a GCD K
- Find GCD of two numbers
- Find pair with maximum GCD in an array in C++
- Program to find largest distance pair from two list of numbers in Python
- Find any pair with given GCD and LCM in C++
- Java Program to Find GCD of two Numbers
- Swift Program to Find GCD of two Numbers
- Kotlin Program to Find GCD of two Numbers
- Program to compute gcd of two numbers recursively in Python
- Program to find GCD of floating point numbers in C++
- Haskell program to find the gcd of two numbers
- GCD of more than two (or array) numbers in Python Program
- Find two numbers whose sum and GCD are given in C++
- Program to find GCD or HCF of two numbers in C++