- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Greatest common divisors in Python
Suppose we have a list of positive numbers called nums, we have to find the largest positive number that divides each of the number.
So, if the input is like [14,28,70,56], then the output will be 14.
To solve this, we will follow these steps −
- ans := first element of nums
- for each x in nums, do
- ans := gcd of ans and x
- return ans
Let us see the following implementation to get better understanding −
Example
import math class Solution: def solve(self, nums): ans = nums[0] for x in nums: ans = math.gcd(ans, x) return ans ob = Solution() print(ob.solve([14,28,70,56]))
Input
[14,28,70,56]
Output
14
- Related Articles
- Greatest Common Divisor of Strings in Python
- Python Program for Common Divisors of Two Numbers
- Program to count number of common divisors of two numbers in Python
- Find the lowest common denominator or greatest common factor in Excel
- Return the greatest common divisor and lowest common multiple in Numpy
- C++ Program for Common Divisors of Two Numbers?
- Java Program for Common Divisors of Two Numbers
- C++ Program for the Common Divisors of Two Numbers?
- Count the number of common divisors of the given strings in C++
- Count divisors of n that have at-least one digit common with n in Java
- Program to maximize number of nice divisors in Python
- Python – Replacing by Greatest Neighbors in a List
- Closest Divisors in C++
- Four Divisors in C++
- Check if count of divisors is even or odd in Python

Advertisements