1 solutions

  • 0
    @ 2025-8-3 15:21:23

    gcd&xor

    设满足条件的数对是 a,ba,b,满足 g=gcd⁡(a,b)=a⊕bg = \gcd(a,b) = a\oplus b。

    算法一

    直接枚举两个数并判断。

    时间 O(n2log⁡n)O(n^2\log n)。预处理最大公约数的话就是 O(n2)O(n^2)。

    算法二

    先枚举 gg,再枚举 gg 的倍数作为 aa。那么根据异或的性质必然有 b=a⊕gb=a\oplus g,直接判断即可。

    枚举数量等于 nn 以内一对倍数的数对个数,等于 $\sum_{g=1}^n \lfloor\frac{n}{g}\rfloor = O(n\log n)$。暴力求最大公约数的话总时间是 O(nlog⁡2n)O(n\log^2 n)。

    算法三

    仔细考虑一下:当 a=ba=b 时 a⊕b=0a\oplus b=0 不可能满足条件。当 a≠ba\ne b 时,gcd⁡(a,b)≤∣a−b∣≤a⊕b\gcd(a,b) \le \lvert a-b\rvert \le a\oplus b。所以满足条件当且仅当两者都等于 ∣a−b∣\lvert a-b\rvert。这样在算法二基础上检查的时间变为 O(1)O(1),总时间变为 O(nlog⁡n)O(n\log n)。

    思考:这个题的约束实际上限制更强。想一想,你能否继续降低枚举数量得到更低的复杂度?(没有标准答案。)

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int n;
    
    int main()
    {
        freopen("gcdxor.in", "r", stdin);
        freopen("gcdxor.out", "w", stdout);
        ios::sync_with_stdio(false);
    
        cin >> n;
    
        int ans = 0;
        for (int c = 1; c <= n; ++c)
        {
            for (int a = 2 * c; a <= n; a += c)
            {
                if ( (a ^ c) == a - c )
                    ++ans;
            }
        }
        cout << ans << endl;
        return 0;
    }
    
    • 1

    Information

    ID
    26
    Time
    1000ms
    Memory
    512MiB
    Difficulty
    8
    Tags
    (None)
    # Submissions
    12
    Accepted
    10
    Uploaded By