POJ 2048 Longge's problem (尤拉函式 積性函式)

_TCgogogo_發表於2015-09-10

Longge's problem
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 7550   Accepted: 2500

Description

Longge is good at mathematics and he likes to think about hard mathematical problems which will be solved by some graceful algorithms. Now a problem comes: Given an integer N(1 < N < 2^31),you are to calculate ∑gcd(i, N) 1<=i <=N.

"Oh, I know, I know!" Longge shouts! But do you know? Please solve it.

Input

Input contain several test case.
A number N per line.

Output

For each N, output ,∑gcd(i, N) 1<=i <=N, a line

Sample Input

2
6

Sample Output

3
15

Source

POJ Contest,Author:Mathematica@ZSU


題目連結:http://poj.org/problem?id=2480


題目大意:∑gcd(i, N) 1<=i <=N


題目分析:∑gcd(i, N) = ∑(d|N) d*phi[N/d]

很好理解,phi[N / d]就是1 - N中與N最大公約數為d的個數,因為phi[n]表示小於等於n且與n互質的數的個數,那麼n除去d這個因子後所求的尤拉函式值正是乘了d以後與N最大公約數為d的數的個數所以直接用公式即可,注意要用long long,這種姿勢能在200ms+解決這個問題

#include <cstdio>
#define ll long long

ll phi(ll x)
{   
    ll res = x;
    for(ll i = 2; i * i <= x; i ++)
    {
        if(x % i == 0)
        {
            res = res / i * (i - 1);
            while(x % i == 0)
                x /= i;
        }
    }
    if(x > 1)
        res = res / x * (x - 1);
    return res;
}

int main()
{
    ll n;
    while(scanf("%lld", &n) != EOF)
    {
        ll ans = 0;
        for(ll i = 1; i * i <= n; i++)
        {   
            if(n % i == 0)
            {
                ans += i * phi(n / i);
                if(i * i != n)
                    ans += n / i * phi(i);
            }
        }
        printf("%lld\n", ans);
    }
}


解法二:設:F(N)=∑gcd(i, N) ,1<=i<=N

F(N)是積性函式,這裡不做證明了,N = p1^a1 * p2^a2 * p3^a3 * ... * pk^ak

則F(N) = F(p1^a1) * F(p2^a2) * ... * F(pk^ak)

F(p^a) = ∑(p^ai|p^a)  p^ai * phi[p^(a - ai)] = phi[p^a] + p*phi[p^(a - 1)] + .., p^a*phi[1]

又因為phi[p^a] = (p - 1) * (p ^ (a - 1))

F(p^a) = (p - 1) * (p^(a - 1)) + (p - 1) * p * (p^(a - 2)) + ... + (p - 1) * p^(a - 1) + p^a

           = a * (p - 1) * p^(a - 1) + p^a

           = (ap - a + p) * p^(a - 1)

累乘即可,注意如果n本身就是素數,則有F(n) = 2 * n - 1

#include <cstdio>
#define ll long long

int main()
{
    ll n;
    while(scanf("%lld", &n) != EOF)
    {
        ll ans = 1;
        for(ll i = 2; i * i <= n; i++)
        {   
            if(n % i == 0)
            {
                ll cnt = 0, tmp = 1;
                while(n % i == 0)
                {
                    n /= i;
                    cnt ++;
                    tmp *= i;
                }
                ans *= (cnt * i - cnt + i) * (tmp / i);
            }
        }
        if(n != 1)
            ans *= 2 * n - 1;
        printf("%lld\n", ans);
    }
}



相關文章