最大Gcd和总和

时间:2017-07-24 10:38:14

标签: algorithm python-3.x greatest-common-divisor

您将获得两个数组:A和B.每个数组包含" N"每个元素。选择一对元素,以便: X属于Array A

Y属于Array B GCD(X,Y)是所有对(X,Y)的最大值。

这是来自Hackerrank的问题weekcodeof 34。

from fractions import gcd

from itertools import product
n = int(input().strip()) #two arrays of equal length
A = set(map(int, input().strip().split(' '))) #array1
B = set(map(int, input().strip().split(' '))) # arry2
output_sum=[]
output_GCD=[]
c=list(product(A,B))
for i in c:

    temp1=i[0]
    temp2=i[1]

    sum_two=temp1+temp2

    temp3=gcd(temp1,temp2)
    output_GCD.append(temp3)
    output_sum.append(temp1+temp2)
temp=[]
for i in range(len(output_GCD)):
  if(output_GCD[i]==max(output_GCD)):
    temp.append(output_sum[i])
print(max(temp))

此解决方案适用于较小的条件,我在大多数测试用例中都已超时,请帮助我如何改进我的解决方案。

2 个答案:

答案 0 :(得分:1)

您可以通过下一种方式计算数组a_divisors的所有除数A

# it is not real python-code, just ideas of algorithm
count = {}
for (i : A): 
  count[i]++

a_divisors = {}
for (i : range(1, 10^6)):
  for (j = i * i; j <= 10^6; j += i):
    if j in count.keys():
      a_divisors[i] = 1

b_divisors构建相同的数组B后,从两个数组中选择公共最大值后

例如:

5
3 1 4 2 8
5 2 12 8 3

产生除数数组:

a: 1, 2, 3, 4, 8
b: 1, 2, 3, 4, 5, 6, 8, 12

共同最大值是:4

如果您知道gcd(a, b) = 4,则只需从A中选择1个具有除数4和1来自B的最大值:8 + 12 = 16

答案 1 :(得分:0)

您必须将A和B转换为Set(以便在其中轻松找到)

def maximumGcdAndSum(A, B):
    A = set(A)
    B = set(B)
    max_nbr = max(max(A), max(B))
    i = max_nbr

    while i > 0:  # for each i starting from max number
        i_pow = i  # i, i^2, i^3, i^4, ...
        maxa = maxb = 0

        while i_pow <= max_nbr:  # '<=' is a must here
            if i_pow in A:
                maxa = i_pow  # get the max from power list which devides A
            if i_pow in B:
                maxb = i_pow  # get the max from power list which devides B
            i_pow += i
        if maxa and maxb:
            return maxa + maxb  # if both found, stop algorithm
        i -= 1

    return 0