"Algorithm Competition·Quick 300 Questions" One question per day: "Least Common Multiple"

" Algorithm Competition: 300 Quick Questions " will be published in 2024 and is an auxiliary exercise book for "Algorithm Competition" .
All questions are placed in the self-built OJ New Online Judge .
Codes are given in three languages: C/C++, Java, and Python. The topics are mainly mid- to low-level topics and are suitable for entry-level and advanced students.


" Least common multiple ", link: http://oj.ecustacm.cn/problem.php?id=1820

Question description

[Problem description] Given a number n, ask whether there is an interval l, r such that n is equal to the least common multiple of all numbers in the entire interval.
[Input format] The first line is a positive integer T, indicating that there are T sets of test data, 1≤T≤10000.
   For each set of test data, enter an integer representing the number n, 1≤n≤10^18.
[Output format] For each set of test data, if there is an interval [l, r] as the answer, then output two numbers l and r.
   If there are multiple sets of solutions, output the solution with the smallest l. If there are still multiple solutions and l is the same, the solution with the smallest r is output.
   If there is no solution, output -1.
【Input sample】

3
12
504
17

【Output sample】

1 4
6 9
-1

answer

   If you directly calculate [L, R] corresponding to n, you can only violently search for all possible combinations, which requires a huge amount of calculation. It is easy to think of a simpler method: do the reverse calculation, first precalculate all n corresponding to [L, R], and then query the corresponding [L, R] for the input n.
   But directly traversing all [L, R], the amount of calculation is still very large. The maximum possible value of L and R is n ≤ 1 0 18 = 1 0 9 \sqrt{n}≤ \sqrt{10^{18}}=10^9n 1018 =109 . Traverse all L and R, the calculation amountis O ( nn ) = O ( n ) O(\sqrt{n}\sqrt{n}) = O(n)O(n n )=O ( n ) , timeout.
   If there are at least 3 numbers in [L, R], that is, at least [L, L+1, L+2], then the maximum value of L is n 3 ≤ 1 0 6 \sqrt[3]{n} ≤ 10 ^63n 106 , the amount of calculation is greatly reduced.
   As for the interval [L, L+1] containing only 2 numbers, it can be checked separately, and the calculation amount is very small. Enter a value of n and check thatnn + 1 = n \sqrt{n}\sqrt{n+1}=nn n+1 =It only matters whether n is established.
[Key point]GCD.

C++ code

   Use map to store calculation results. The answer corresponding to n is [L, R] that is stored in the map for the first time.

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
map<ll, pair<int,int>>ans;
void init(){
    
            //预处理,ans[n]表示n对应的答案[L,R],区间内至少3个数
    for(ll L = 1; L <= 2000000; L++)   {
    
    
        ll n = L * (L + 1);
        for(ll R = L + 2; ;R++)   {
    
    
            ll g = __gcd(n, R);
            if(n / g > INF / R)    break;
            n = n / g * R;           //先除再乘,防止溢出
            if(!ans.count(n))        //res这个数还没有算过,存起来
                ans[n] = make_pair(L, R);
        }
    }
}
int main(){
    
    
    init();
    int T;  scanf("%d",&T);
    while(T--) {
    
    
        ll n;  scanf("%lld",&n);
        //先特判区间长度为2的情况: [L,L+1]
        ll sqrt_n = sqrt(n + 0.5);
        pair<int,int>res;
        if(sqrt_n * (sqrt_n + 1) == n)   {
    
    
            res = make_pair(sqrt_n, sqrt_n + 1);
            if(ans.count(n))
                if(res.first > ans[n].first)
                    res = ans[n];
        }
        else if(ans.count(n)) res = ans[n];
        else {
    
     puts("-1"); continue; }
        printf("%d %d\n", res.first, res.second);
    }
    return 0;
}

Java code

import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
class Main{
    
    
    static class Pair<T1, T2> {
    
    
        public T1 first;
        public T2 second;
        public Pair(T1 first, T2 second) {
    
    
            this.first = first;
            this.second = second;
        }
    }

    static final long INF = 1000000000000000000L;
    static Map<Long, Pair<Integer,Integer>> ans;
    static void init() {
    
    
        ans = new HashMap<>();
        for (long L = 1; L <= 2000000; L++) {
    
    
            long n = L * (L + 1);
            for (long R = L + 2; ; R++) {
    
    
                long g = gcd(n, R);
                if (n / g > INF / R) break;
                n = n / g * R;
                if (!ans.containsKey(n)) 
                    ans.put(n, new Pair<Integer,Integer>((int)L, (int)R));
            }
        }
    }
    static long gcd(long a, long b) {
    
     return b == 0 ? a : gcd(b, a % b);}
    public static void main (String[] args) throws java.lang.Exception  {
    
    
        init();
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while (T-- > 0) {
    
    
            long n = sc.nextLong();
            long sqrt_n = (long)Math.sqrt(n + 0.5);
            Pair<Integer,Integer> res;
            if (sqrt_n * (sqrt_n + 1) == n) {
    
    
                res = new Pair<Integer,Integer>((int)sqrt_n, (int)(sqrt_n + 1));
                if (ans.containsKey(n)) {
    
    
                    if (res.first > ans.get(n).first)  res = ans.get(n);
                }
            } else {
    
    
                if (ans.containsKey(n)) res = ans.get(n);
                else {
    
    
                    System.out.println("-1");
                    continue;
                }
            }
            System.out.println(res.first + " " + res.second);
        }
    }
}

Python code

   Use a dictionary to store calculation results, and the answer corresponding to n is [L, R] stored in the dictionary for the first time.

 import math
INF = 10**18
ans = {
    
    }
def init():
    global ans
    for L in range(1, 2000000+1):
        n = L * (L + 1)
        R = L + 2
        while True:
            g = math.gcd(n, R)
            if n // g > INF // R: break
            n = n // g * R
            if n not in ans:   ans[n] = (L, R)
            R += 1
init()
T = int(input())
for _ in range(T):
    n = int(input())
    sqrt_n = int(math.sqrt(n + 0.5))
    if sqrt_n * (sqrt_n + 1) == n:
        res = (sqrt_n, sqrt_n + 1)
        if n in ans:
            if res[0] > ans[n][0]:
                res = ans[n]
    else:
        if n in ans:   res = ans[n]
        else:
            print("-1")
            continue
    print(res[0], res[1])

Guess you like

Origin blog.csdn.net/weixin_43914593/article/details/132427970