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\$.
Constraints:
- \$1 \le N \le 5 \times 10^5\$
- \$1 \le A_i \le 10^6\$
- \$1 \le B_i \le 10^6\$
Input Format
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\$.
Output Format
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=[1]
sums=[]
prodC = itertools.product(*C)
for element in prodC:
gcdVal = math.gcd(element[0],element[1])
D.append((gcdVal,sum(element)))
gcds.append(gcdVal)
# sums.append(sum(element))
# print(D)
maxGCD = max(gcds)
sumsL = [1]
#print(gcds)
# print(sums)
for i in D:
if i[0] == maxGCD:
sumsL.append(i[1])
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 -
16
Output Obtained -
16