P6583 回首过去 题解

· · 题解

如果一个分数化成小数是有限的,则这个分数约分后的分母只能含有质因子 2 和 5。

假设这个分数为:

\frac{bc}{ac}

保证 a = 2^n \times 5^m,(c,2)=(c,5)=1,b \in \mathbb{N}^{+}。

\text{80 pts: }

我们可以枚举 c,那么 a 不能超过 \left\lfloor \frac{n}{c} \right\rfloor,满足条件的 a 的个数可以预处理求出来。b 是不超过 \left\lfloor \frac{n}{c} \right\rfloor 的所有数字,所以我们可以枚举 c 求出方案数,总复杂度 O(n),想 AC 还需要优化。

\text{100 pts: }

预处理 $\text{Time Complexity: }O(\log_2n·\log_5n)$。 计算答案 $\text{Time Complexity: }O(\sqrt{n})$。 $\text{AC Code: }
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

long long _maxi = 0;
long long _res = 0;

int main () {

    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);

    cin >> _maxi;

    vector<long long> theList;

    // find all num that only 2|num or 5|num 
    for (long long i = 1; i < _maxi + 1; i *= 2) {
        for (long long m = i; m < _maxi + 1; m *= 5) {
            theList.push_back(m);
        }
    }

    sort(theList.begin(), theList.end());

    long long numA = theList.size();

    for (long long left = 1, right = 0; left < _maxi + 1; left = right + 1) {
        long long num = _maxi / left; // floor(n / c)

        right = _maxi / num;

        // find a num that <= num
        while (theList[numA - 1] > num) {
            numA--;
        }

        long long numC = right - left + 1; // all [l, r]
        long long num2 = right / 2 - (left - 1) / 2; // n∈[l, r], 2 | n
        long long num5 = right / 5 - (left - 1) / 5; // n∈[l, r], 5 | n 
        long long num10 = right / 10 - (left - 1) / 10; // n∈[l, r], 10 | n 

        numC -= (num2 + num5 - num10); // c num
        _res += num * numA * numC; // update res
    }

    cout << _res << '\n';

    return 0;

}