AC - GCD On Blackboard

Authors: Andrew Cheng, Mohammad Nour Massri, David Zhang

Table of Contents

SolutionImplementation

Solution

The problem asks us to find the maximum possible GCD of the remaining N1N-1 numbers after taking any one of them away. Naively trying every single combination will result in a complexity of O(N2+Nlog(maxai))\mathcal{O}(N^2 + N \log(\max a_i)) as there are NN different ways to take away a number and calculating the GCD will take O(N+log(maxai))\mathcal{O}(N+\log(\max a_i)) time per case.

To speed this process up, we can calculate the GCDs of every prefix and suffix. Let l[i]=gcdj=1ia[j]l[i] = \gcd_{j=1}^{i} a[j] and r[i]=gcdj=iNa[j]r[i] = \gcd_{j=i}^{N} a[j]. Then the answer is the maximum of gcd(l[i1],r[i+1]),\gcd(l[i-1],r[i+1]), i[1,N]i \in [1,N].

Time Complexity: O(N+log(maxai))\mathcal{O}(N+\log(\max a_i))

Time Complexity Proof

Implementation

C++

#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5 + 5;
int arr[maxN];
int prefGcd[maxN]; // prefGcd[i] = GCD of a1,a2, ..., ai
int suffGcd[maxN]; // suffGcd[i] = GCD of ai, ai+1, ..., an
int N;

Python

from math import gcd
n = int(input())
arr = list(map(int, input().split()))
ans = 0
prefix_gcd = [0] * n
prefix_gcd[0] = arr[0]

Java

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Kattio io = new Kattio();
int n = io.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = io.nextInt(); }

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!