Olympiad in Informatics

POJ2480: Longge's Problem — Solution

Main Idea and Conclusions

Given \(n\), compute \(\sum_{i=1}^{n} \gcd(i,n)\).

The statement is really refreshingly clean, but deriving the formulas was heartbreaking. At first I used the table-printing approach, and never managed to find the pattern in it. So the ability to derive formulas really is quite important.

Let's analyze it. For \(i\in [1,n], gcd(i,n)=1\), their contribution to the answer is \(\phi(n)\). Next, look at the other part, that is, \(j\in [1,n], gcd(j,n)=k, k \neq 1\). We can divide it out, turning it into \(k*gcd(\frac{j}{k},\frac{n}{k})=k, gcd(\frac{j}{k},\frac{n}{k})=1\), where by Euler's theorem there are \(\phi(k)\) such \(gcd\), so we derive \(k*\phi(k)\). In the end, the answer just needs to sum the divisors of \(k\) times \(\phi(因数)\).

Finally, you can consider using a map to record the Euler values already computed, which gives a constant-factor optimization.

Code

// POJ2480.cpp
#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#define ll long long
using namespace std;
map<ll, ll> prefix;
vector<ll> getFracted(ll x)
{
    vector<ll> res;
    for (ll i = 1; i * i <= x; i++)
        if (x % i == 0)
        {
            res.push_back(i);
            if (i != x / i)
                res.push_back(x / i);
        }
    return res;
}
ll phi(ll x)
{
    ll ans = x;
    for (ll i = 2; i * i <= x; i++)
        if (x % i == 0)
        {
            ans -= ans / i;
            while (x % i == 0)
                x /= i;
        }
    if (x > 1)
        ans -= ans / x;
    return ans;
}
int main()
{
    ll n;
    while (scanf("%lld", &n) != EOF)
    {
        ll ans = 0;
        vector<ll> container = getFracted(n);
        ll siz = container.size();
        for (int i = 0; i < siz; i++)
        {
            if (!prefix.count(n / container[i]))
                prefix[n / container[i]] = phi(n / container[i]);
            ll e = prefix[n / container[i]];
            ans += e * container[i];
        }
        printf("%lld\n", ans);
    }
    return 0;
}

src: https://www.cnblogs.com/neopenx/p/4095691.html