Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7550 | Accepted: 2500 |
Description
"Oh, I know, I know!" Longge shouts! But do you know? Please solve it.
Input
A number N per line.
Output
Sample Input
2
6
Sample Output
3
15
Source
题目链接: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);
}
}