欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

51nod1238 最小公倍数之和 V3(莫比乌斯反演)

程序员文章站 2022-10-06 11:03:29
题意 "题目链接" Sol 不想打公式了,最后就是求一个 $\sum_{i=1}^n ig(\frac{N}{i})$ $g(i) = \sum_{i=1}^n \phi(i) i^2$ 拉个$id2$卷一下 "这个博客推的狠详细" cpp include define int long long ......

题意

题目链接

sol

不想打公式了,最后就是求一个

\(\sum_{i=1}^n ig(\frac{n}{i})\)

\(g(i) = \sum_{i=1}^n \phi(i) i^2\)

拉个\(id2\)卷一下

#include<bits/stdc++.h> 
#define int long long 
#define ll long long 
using namespace std;
const int maxn = 1e6 + 10, mod = 1e9 + 7, inf = 1e9 + 10, inv2 = 500000004, inv6 = 166666668, b = 1e6;
template <typename a, typename b> inline ll add(a x, b y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename a, typename b> inline void add2(a &x, b y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename a, typename b> inline ll mul(a x, b y) {return 1ll * x * y % mod;}
template <typename a, typename b> inline void mul2(a &x, b y) {x = (1ll * x * y % mod + mod) % mod;}
void print(int x) {
    if(!x) return ;
    print(x / 10);
    putchar(x % 10 + '0');
}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = 1ll * x * 10 + c - '0', c = getchar();
    return x * f;
}
int g[maxn], phi[maxn], mu[maxn], vis[maxn], prime[maxn], tot;
map<int, int> mp;
int sum(int n) {return mul(mul(n % mod, add(n, 1)), inv2);}
int sum2(int n) {return mul(mul(n % mod, mul(add(n, 1), mul(2, n) + 1)), inv6);}
int sum3(int n) {return mul(sum(n), sum(n));}
void sieve(int n) {
    vis[1] = phi[1] = mu[1] = 1;
    for(int i = 2; i <= n; i++) {
        if(!vis[i]) prime[++tot] = i, mu[i] = -1, phi[i] = i - 1;
        for(int j = 1; j <= tot && i * prime[j] <= n; j++) {
            vis[i * prime[j]] = 1;
            if(i % prime[j]) phi[i * prime[j]] = phi[i] * phi[prime[j]], mu[i * prime[j]] = -mu[i];
            else {mu[i * prime[j]] = 0; phi[i * prime[j]] = phi[i] * prime[j]; break;};
        }
    }
    for(int i = 1; i <= n; i++) g[i] = add(g[i - 1], mul(phi[i], mul(i, i)));
}
ll dsieve(int n) {
    if(n <= b) return g[n];
    else if(mp[n]) return mp[n];
    ll t = sum3(n);
    for(int i = 2, nxt; i <= n; i = nxt + 1) {
        nxt = n / (n / i); 
        add2(t, -mul(add(sum2(nxt), -sum2(i - 1)), dsieve(n / i)));
    }
    return mp[n] = t;
}
signed main() {
    sieve(b);
    int n = read(), ans = 0;
    for(int i = 1, nxt; i <= n; i = nxt + 1) {
        nxt = n / (n / i);
        add2(ans, mul(add(sum(nxt), -sum(i - 1)), dsieve(n / i)));
    }
    print(ans);
    return 0;
}