Suppose we have a list of elements called nums, we have to find the largest positive value that divides each of the integers.
So, if the input is like nums = [15, 81, 78], then the output will be 3, as 3 is the largest integer that divides all 15, 81, and 78.
To solve this, we will follow these steps −
if size of nums is same as 1, then
return nums[0]
div := gcd of nums[0] and nums[1])
if size of nums is same as 2, then
return div
for i in range 1 to size of nums - 2, do
div := gcd of div and nums[i + 1]
if div is same as 1, then
return div
return div
Example
Let us see the following implementation to get better understanding
from math import gcd def solve(nums): if len(nums) == 1: return nums[0] div = gcd(nums[0], nums[1]) if len(nums) == 2: return div for i in range(1, len(nums) - 1): div = gcd(div, nums[i + 1]) if div == 1: return div return div nums = [15, 81, 78] print(solve(nums))
Input
[15, 81, 78]
Output
3