GCD#137

GCD (Editorial)

It is known that

GCD (a_1, a_2, ..., a_i) = GCD (GCD (a_1, a_2, ..., a_{i - 1}) , a_i)

Based on this, the greatest common divisor of two, three, ..., numbers can be computed sequentially. For example, for four numbers, the following equality holds:

GCD (a_1, a_2, a_3, a_4) = GCD (GCD (GCD (GCD (0, a_1), a_2), a_3), a_4)

Algorithm implementation

The function gcd computes the greatest common divisor.

int gcd(int a, int b)
{
  return (!b) ? a : gcd(b, a % b);
}

Read the input data and sequentially compute the GCD for the given numbers, storing the result in the variable .

res = 0;
scanf("%d", &n); 
while (n--)
{
  scanf("%d", &b);
  res = gcd(res, b);
}

Print the answer.

printf("%d\n", res);

Python implementation

import math

Read the input data.

n = int(input())
lst = list(map(int,input().split()))

In the variable , sequentially compute the GCD of the given numbers.

res = 0
for x in lst:
  res = math.gcd(res, x)

Print the answer.

print(res)