Java教程

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

本文主要是介绍51nod1238 最小公倍数之和 V3(莫比乌斯反演),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题意

题目链接

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;
}
这篇关于51nod1238 最小公倍数之和 V3(莫比乌斯反演)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!