Home » Python » Python programs

# Python program to find the GCD of the array

Here, we will learn **how to find the greatest common divisor (GCD) of the array elements in the Python programming language?**

Submitted by Bipin Kumar, on November 19, 2019

**GCD** of two or more non-zero number is the largest number that divides both or more non-zero numbers. It is one of the basic concepts of mathematics.

**Example:**

Input : 8, 4 Output : 4 Explanation: 8 and 4 are two non-zero numbers which are divided by 2 and also by 4 but 4 is the largest number than 2. So, theGCD of 8 and 4 is 4.

Here, an array of the non-zero numbers will be provided by the user and we have to find the **GCD of the array elements in Python**. To solve this problem, we will use the math module of Python. It is one of the most useful modules of Python used for mathematical operations. So, before going to solve this we will learn how to find the GCD of two non-zero numbers.

**Python program to find the GCD of two non-zero numbers**

# importing the module import math # input two numbers m,n=map(int,input('Enter two non-zero numbers: ').split()) #to find GCD g=math.gcd(m,n) # printing the result print('GCD of {} and {} is {}.'.format(m,n,g))

**Output**

Run 1: Enter two non-zero numbers: 8 4 GCD of 8 and 4 is 4. Run 2: Enter two non-zero numbers: 28 35 GCD of 28 and 35 is 7.

Now, we have learned to find the GCD of two non-zero number but our main task is to find the GCD of an array element or more than two non-zero numbers. So, let's go to write a Python program by simply using the above concepts.

**Python program to find the GCD of the array**

# importing the module import math # array of integers A=[40,15,25,50,70,10,95] #initialize variable b as first element of A b=A[0] for j in range(1,len(A)): s=math.gcd(b,A[j]) b=s print('GCD of array elements is {}.'.format(b))

**Output**

GCD of array elements is 5.

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.