It is known that
Based on this, the greatest common divisor of two, three, ..., numbers can be computed sequentially. For example, for four numbers, the following equality holds:
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 mathRead 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)