XiaoHuang's Space
XiaoHuang's Space
XiaoHuang
May the force be with you.
『题解』洛谷P1891 疯狂LCM
Posted: Dec 11, 2019
Last Modified: Jan 22, 2020
This article was last modified days ago. The content of this post may be outdated!

Portal

Portal: Luogu

Description

众所周知,czmppppp是数学大神犇。一天,他给众蒟蒻们出了一道数论题,蒟蒻们都惊呆了。。。

给定正整数$N$,求LCM(1, N) + LCM(2, N) + ... + LCM(N, N)

Input

第一行一个数$T$,表示有$T$组数据。

对于每组数据,一行,一个正整数$N$。

Output

$T$行,每行为对应答案。

Sample Input

3
1
2
5

Sample Output

1
4
55

Hint

对于$30\%$的数据,$1 \le T \le 5$,$1 \le N \le 100000$;

对于$100\%$的数据,$1 \le T \le 300000$,$1 \le N \le 1000000$。

Solution

题目中的式子可以化简为:

$$\begin{aligned} \sum^{n}_{i = 1}{\text{lcm}(i, n)} & = \sum^{n}_{i = 1}{\frac{i \times n}{\gcd(i, n)}} \\ & = n \times \sum^{n}_{i = 1}{\frac{i}{\gcd(i, n)}} \\ & = n \times \sum_{d | n}\sum_{i = 1}^{n}\frac{i}{d} \times (d == \gcd(i, n)) \\ & = \frac{n}{d} \times \sum_{d | n}\sum^{n}_{i = 1}d == \gcd(i, n) \end{aligned} \\\ \text{当}\gcd(i, n) == 1 \text{时,} \gcd(n - i, n) == 1 (i, n - i \ne 1) \\ \therefore \frac{n}{d} \times \sum_{d | n}\sum^{n}_{i = 1}d == \gcd(i, n) \\ = \sum_{i = 1}^{n}i \times (\gcd(i, n) == 1)= n \times \frac{\varphi(d)}{2}$$

Code

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>

using namespace std;

typedef long long LL;
const int MAXN = 1000005;
int T;
LL n, cnt, ans[MAXN], phi[MAXN], prime[MAXN];
inline void calc_phi() {//计算phi函数
    phi[1] = 1;
    for (int i = 2; i <= MAXN; i++) {
        if (!phi[i]) {
            prime[++cnt] = i;
            phi[i] = i - 1;
        }
        for (int j = 1; j <= cnt; j++) {
            if (i * prime[j] >= MAXN) break;
            if (i % prime[j] == 0) {
                phi[i * prime[j]] = phi[i] * prime[j];
                break;
            } else phi[i * prime[j]] = phi[i] * (prime[j] - 1);
        }
    }
}
int main() {
    scanf("%d", &T);
    calc_phi();
    for (int i = 1; i <= MAXN; i++)
        for (int j = i; j <= MAXN; j += i)
            ans[j] += phi[(j / i)] * (j / i) + 1 >> 1;//最后推出的式子
    while (T--) {
        scanf("%lld", &n);
        printf("%lld\n", n * ans[n]);//最后主题要×n
    }
    return 0;
}
Article License: CC BY-NC-ND 4.0
Article Author: XiaoHuang
  1. 1. Portal
  2. 2. Description
  3. 3. Input
  4. 4. Output
  5. 5. Sample Input
  6. 6. Sample Output
  7. 7. Hint
  8. 8. Solution
  9. 9. Code
Newer Post
『题解』洛谷P1993 小K的农场
Older Post
『题解』洛谷P1351 联合权值
Buy me a beer?
-->
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×