POJ 2048 Longge's problem (欧拉函数 积性函数)

来源:互联网 发布:mac网络恢复 分区 编辑:程序博客网 时间:2024/05/17 04:24

Longge's problem
Time Limit: 1000MS Memory Limit: 65536KTotal 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

26

Sample Output

315

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 longll 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 longint 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);    }}



0 0
原创粉丝点击