- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements