Hướng giải của Tổng GCD


Nhớ rằng hướng dẫn giải này chỉ nên sử dụng khi bế tắc, và tuyệt đối không nên sao chép mã nguồn kèm theo. Hãy tôn trọng tác giả bài tập và người viết hướng dẫn giải.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.

Ý tưởng: S(N) = ∑_{i=1}^{N} gcd(i, N). Với mỗi ước d của N, có φ(N/d) số i trong [1,N] mà gcd(i,N) = d. Vậy S(N) = ∑_{d|N} d × φ(N/d). Phân tích N ra thừa số nguyên tố và duyệt ước.

Độ phức tạp: O(√N) thời gian, O(1) bộ nhớ.

C++ cpp #include <bits/stdc++.h> using namespace std; using ll = long long; const ll MOD = 1e9 + 7; ll phi(ll n) { ll res = n; for (ll i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) n /= i; res -= res / i; } } if (n > 1) res -= res / n; return res; } ll solve(ll n) { ll res = 0; for (ll i = 1; i * i <= n; i++) { if (n % i == 0) { ll d1 = i, d2 = n / i; res = (res + d1 % MOD * phi(d2)) % MOD; if (d1 != d2) res = (res + d2 % MOD * phi(d1)) % MOD; } } return res; } int main() { ios::sync_with_stdio(0); cin.tie(0); ll n; cin >> n; cout << solve(n) << "\n"; return 0; }
Python python MOD = 10**9 + 7 def phi(n): res = n i = 2 while i * i <= n: if n % i == 0: while n % i == 0: n //= i res -= res // i i += 1 if i == 2 else 2 if n > 1: res -= res // n return res n = int(input()) ans = 0 i = 1 while i * i <= n: if n % i == 0: d1, d2 = i, n // i ans = (ans + d1 * phi(d2)) % MOD if d1 != d2: ans = (ans + d2 * phi(d1)) % MOD i += 1 print(ans % MOD)

Nhận xét

Không có ý kiến tại thời điểm này.