Sum of GCD#6941

Sum of GCD (Editorial)

For each test, store the set of input numbers in the array. Then, for each pair (i, j)~(0 \le i < j < m) calculate the GCD (mas[i], mas[j]) and add it to the overall sum.

Example

For the third test case, the answer is

GCD(125,15) + GCD(125,25) + GCD(15,25) = 5 + 25 + 5 = 35

Algorithm implementation

Store the input numbers in the array.

#define MAX 110
int m[MAX];

The gcd function returns the greatest common divisor of the numbers and .

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

The main part of the program. Read the number of test cases .

scanf("%d", &tests);
while (tests--)
{

Read the input data for each test case.

  scanf("%d", &n);
  for (i = 0; i < n; i++)
    scanf("%d", &m[i]);

Compute the desired sum in the variable .

  res = 0;

Iterate through all possible pairs of indices such that 0 \le i < j < n, and for each pair compute the GCD (m[i], m[j]) and add this value to .

  for (i = 0; i < n; i++)
  for (j = i + 1; j < n; j++)
    res += gcd(m[i], m[j]);

Print the answer.

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

Python implementation

Read the number of test cases .

tests = int(input())

Read the input data for each test case.

for _ in range(tests):
  n, *lst = list(map(int, input().split()))

Compute the desired sum in the variable .

  res = 0

Iterate through all possible pairs of indices such that 0 \le i < j < n, and for each pair compute the GCD (m[i], m[j]) and add this value to .

  for i in range(n):
    for j in range(i + 1, n):
      res += math.gcd(lst[i], lst[j])

Print the answer.

  print(res)