Solution 1
The naive approach would be to brute-force each pair of numbers in the array and calculate the maximum GCD. Sadly, this solution gets TLE on around half of the test cases.
Implementation
Time Complexity:
from math import gcdn = int(input())arr = list(map(int, input().split()))ans = 1for i in range(n - 1):for j in range(i + 1, n):ans = max(ans, gcd(arr[i], arr[j]))print(ans)
Solution 2
Maintain an array, , to store the count of divisors. For each value in the array, find its divisors and for each in those divisors, increment by one. The greatest GCD shared by two elements in the array will be the greatest index in our stored count for divisors with a count greater than or equal to .
Implementation
Time Complexity:
Warning!
Due to the tight time limit, the following Python solution still receives TLE on about half the test cases.
from math import sqrtMAX_VAL = 1000000divisors = [0] * (MAX_VAL + 1)n = int(input())a = list(map(int, input().split()))for i in range(n):up = int(sqrt(a[i]))for div in range(1, up + 1):
Solution 3
Given a value, , we can check whether a pair has a GCD equal to by checking all the multiples of . With that information, loop through all possible values of and check if it is a divisor to two or more values. This works in since
Implementation
Time Complexity:
MAXX = int(1e6 + 5)n = int(input())arr = list(map(int, input().split()))p = [0] * MAXXfor i in range(n):p[arr[i]] += 1for i in range(MAXX, 0, -1):div = 0for j in range(i, MAXX, i):div += p[j]if div >= 2:print(i)break
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!