CF - Orac & LCM

Authors: Benjamin Qi, Timothy Gao


Official Editorial

Solution: Prime Factorization

For each prime, the second-to-lowest exponent of the prime that occurs in any of the numbers in the input is the exponent of this prime that will appear in the final answer.

Here's a short solution that accomplishes this without explicitly computing any prime factorizations!

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll a, b;
// a stores minimum exponents (gcd of all numbers seen so far)
// b stores second minimum exponents
int n;

Java

import java.io.*;
import java.util.*;
public class oraclcm {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] nums = new int[N];

Python

import math
"""
a stores minimum exponents (gcd of all numbers seen so far)
b stores second minimum exponents
"""
def red(): # restore invariant mentioned above
global a, b

If it's hard to understand what exactly this code is doing at first glance, a good first step is to simulating the code in the case where each aia_i is a power of the same prime (say, 2k2^k). If the algorithm works for this case, then it will also work in the general case since the contributions of different primes are computed independently and multiplied together.

Here's another way of thinking about this:

For a fixed jj,

gcd0i<j[lcm(ai,aj)]=lcm(aj,gcd0i<j(ai)),\gcd_{0\le i<j}\left[\text{lcm}(a_i,a_j)\right]=\text{lcm}(a_j,\gcd_{0\le i<j}(a_i)),

and we can update gcd0i<j(ai)\gcd_{0\le i<j}(a_i) when jj increases by one. Taking the GCD of the results for each jj gives the answer.

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!