Skip to content

1 min read中文

Editorial | "LightOJ 1289" LCM from 1 to n

Editorial for LightOJ 1289, computing lcm(1,2,...,n) in O(n) with a linear sieve plus a recurrence relation.

Machine-translated from the Chinese original.

Problem statement backup

Problem

Find lcm(1,2,...,n)\operatorname{lcm}(1,2,...,n), multiple test cases.

Editorial

MicroMaker, resident OI legend, reckoned it had something to do with Euler’s totient function, but I stared at it for a while and came up with nothing. So brute force it is.

First, use a linear sieve to sieve out all primes in 11081\sim 10^8. Then consider the following property:

If n+1=pkn+1=p^k, where pp is a prime, then lcm(1,2,...,n+1)=lcm(1,2,...,n)×p\operatorname{lcm}(1,2,...,n+1)=\operatorname{lcm}(1,2,...,n)\times p; otherwise, lcm(1,2,...,n+1)=lcm(1,2,...,n)\operatorname{lcm}(1,2,...,n+1)=\operatorname{lcm}(1,2,...,n).

Since the time limit for this problem is 44 seconds, once we have the recurrence we can push a hundred million through in O(n)O(n).

Code backup

hero.webp