I've written a program to solve the same problem as Sum of Maximum GCD.
My solution contains working code and it has successfully passed some of the test cases. But it does throw runtime exceptions and I'm trying to understand where I could be going wrong. I don't see any segmentation faults that could be tripping it up.
You are given two arrays \$A\$ and \$B\$ containing \$N\$ elements each. Choose a pair of elements \$x, y\$ such that:
- \$x\$ belongs to array \$A\$.
- y belongs to array \$B\$.
- \$\gcd(x,y)\$ is the maximum of all pairs \$x, y\$.
If there is more than one such pair \$x, y\$ having maximum \$\gcd\$, then choose the one with maximum sum. Print the sum of elements of this maximum-sum pair.
NOTE: \$\gcd(x,y)\$ the largest integer that divides both \$x\$ and \$y\$.
- \$1 \le N \le 5 \times 10^5\$
- \$1 \le A_i \le 10^6\$
- \$1 \le B_i \le 10^6\$
The first line of the input contains n denoting the total number of elements of arrays \$A\$ and \$B\$. Next line contains \$n\$ space separated positive integers denoting the elements of array \$A\$. Next line contains \$n\$ space separated positive integers denoting the elements of array \$B\$.
From all the pairs having maximum gcd, print the sum of one that has the maximum sum.
I'm still actively trying to find the issue, though I think I could benefit from unbiased eyes and criticism to help me better my code.
#!/bin/python3 import sys import itertools import math def maximumGcdAndSum(A, B): C =  C.append(A) C.append(B) D= E= gcds= sums= prodC = itertools.product(*C) for element in prodC: gcdVal = math.gcd(element,element) D.append((gcdVal,sum(element))) gcds.append(gcdVal) # sums.append(sum(element)) # print(D) maxGCD = max(gcds) sumsL =  #print(gcds) # print(sums) for i in D: if i == maxGCD: sumsL.append(i) return max(sumsL) # Complete this function if __name__ == "__main__": n = int(input().strip()) A = list(map(int, input().strip().split(' '))) B = list(map(int, input().strip().split(' '))) res = maximumGcdAndSum(A, B) print(res)
Sample input tried -
5 3 1 4 2 8 5 2 12 8 3
Output Expected -
Output Obtained -