数论|51 NOD 1363 最小公倍数之和 (欧拉函数思维应用)

1363 最小公倍数之和 推式子
【数论|51 NOD 1363 最小公倍数之和 (欧拉函数思维应用)】 ∑ i = 1 n l c m ( i , n ) = n ∑ i = 1 n i g c d ( i , n ) = n ∑ d ∣ n ∑ i = 1 n i d ( g c d ( i , n ) = = d ) = n ∑ d ∣ n ∑ i = 1 n d i ( g c d ( i , n d ) = = 1 ) = n ∑ d ∣ n d ? ( d ) + ( d = = 1 ) 2 \sum_{i = 1} ^{n} lcm(i, n)\\ = n\sum_{i = 1} ^{n} \frac{i}{gcd(i, n)}\\ = n \sum_{d \mid n} \sum_{i = 1} ^{n} \frac{i}{d}(gcd(i, n) == d)\\ = n \sum_{d \mid n} \sum_{i = 1} ^{\frac{n}{d}}i (gcd(i, \frac{n}{d}) == 1)\\ = n \sum_{d \mid n} \frac{d \phi(d) + (d == 1)} {2}\\ i=1∑n?lcm(i,n)=ni=1∑n?gcd(i,n)i?=nd∣n∑?i=1∑n?di?(gcd(i,n)==d)=nd∣n∑?i=1∑dn??i(gcd(i,dn?)==1)=nd∣n∑?2d?(d)+(d==1)?
接下来就是筛出 n \sqrt n n ?内的质数,再通过递归算出所有的因数,然后加上所有的因数对答案的贡献,具体细节在代码中描述。
代码

/* Author : lifehappy */ #pragma GCC optimize(2) #pragma GCC optimize(3) #include #define mp make_pair #define pb push_back #define endl '\n' #define mid (l + r >> 1) #define lson rt << 1, l, mid #define rson rt << 1 | 1, mid + 1, r #define ls rt << 1 #define rs rt << 1 | 1using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair pii; const double pi = acos(-1.0); const double eps = 1e-7; const int inf = 0x3f3f3f3f; inline ll read() { ll f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9') { if(c == '-')f = -1; c = getchar(); } while(c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + (c ^ 48); c = getchar(); } return f * x; }const int N = 1e5 + 10, mod = 1e9 + 7; int prime[N], cnt; bool st[N]; void init() { for(int i = 2; i < N; i++) { if(!st[i]) prime[cnt++] = i; for(int j = 0; j < cnt && i * prime[j] < N; j++) { st[i * prime[j]] = 1; if(i % prime[j] == 0) break; } } }int fac[50], num[50], tot; ll ans; void solve(int pos, int n, int phi) { if(pos == tot + 1) { ans = (ans + 1ll * n * (phi + (n == 1)) / 2 % mod) % mod; //特判n为1的情况。 return ; } solve(pos + 1, n, phi); //不选这个数的情况。 n *= fac[pos], phi *= (fac[pos] - 1); //第一次选这个数要单独考虑,当两个数互质的时候phi[i * prime] = phi[i] * (prime - 1) solve(pos + 1, n, phi); for(int i = 1; i < num[pos]; i++) { n *= fac[pos], phi *= fac[pos]; //这里就是不互质的情况了 solve(pos + 1, n, phi); } }int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); init(); int T = read(); while(T--) { tot = 0; int n = read(), m = n; for(int i = 0; prime[i] * prime[i] <= n; i++) { if(n % prime[i] == 0) { fac[++tot] = prime[i], num[tot] = 0; while(n % prime[i] == 0) { n /= prime[i]; num[tot]++; } } } if(n != 1) { fac[++tot] = n, num[tot] = 1; } ans = 0; solve(1, 1, 1); printf("%lld\n", ans * m % mod); } return 0; }

    推荐阅读