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

Updated on: 23-Sep-2020

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements