4804: 歐拉心算

4804: 歐拉心算

Time Limit: 15 Sec Memory Limit: 256 MB
Submit: 229 Solved: 147
[Submit][Status][Discuss]
Description

給出一個數字N
這裏寫圖片描述

Input

第一行爲一個正整數T,表示數據組數。
接下來T行爲詢問,每行包含一個正整數N。
T<=5000,N<=10^7
Output

按讀入順序輸出答案。
Sample Input

1

10
Sample Output

136
HINT

Source

By FancyCoder

[Submit][Status][Discuss]

大力莫比烏斯反演可以得到
Ans=ni=1nj=1ϕ(gcd(i,j))=ni=1ϕ(i)nid=1μ(d)nid2
g(n)=nd=1μ(d)nd2
注意到ndn1d=1 成立當且僅當d|n
那麼g(n)=g(n1)+d|nμ(d)(2nd1)
由於d|nμ(d)d=ϕ(n)n
g(n)=g(n1)+2ϕ(d)[n=1]
於是Ans=ni=1ϕ(i)g(ni)
複雜度O(TN)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define min(a,b) ((a) < (b) ? (a) : (b))
using namespace std;

const int maxn = 5005;
const int N = 10000007;
typedef long long LL;

int T,n,tot,pri[N],Q[maxn];
LL phi[N],g[N];
bool not_pri[N];

void Solve(int n)
{
    LL Ans = 0;
    for (int i = 1,last; i <= n; i = last + 1)
    {
        int tmp = n / i; last = n / tmp;
        Ans += (phi[last] - phi[i - 1]) * g[tmp];
    }
    printf("%lld\n",Ans);
}

int main()
{
    #ifdef DMC
        freopen("DMC.txt","r",stdin);
    #endif

    cin >> T; phi[1] = g[1] = 1;
    for (int i = 1; i <= T; i++)
        scanf("%d",&Q[i]),n = max(n,Q[i]);
    for (int i = 2; i <= n; i++)
    {
        if (!not_pri[i])
            pri[++tot] = i,phi[i] = i - 1;
        for (int j = 1; j <= tot; j++)
        {
            int Nex = i * pri[j];
            if (Nex > n) break;
            not_pri[Nex] = 1;
            if (i % pri[j] == 0)
            {
                phi[Nex] = phi[i] * pri[j]; break;
            }
            phi[Nex] = phi[i] * (pri[j] - 1);
        }
        g[i] = g[i - 1] + 2LL * phi[i];
    }
    for (int i = 2; i <= n; i++) phi[i] += phi[i - 1];
    for (int i = 1; i <= T; i++) Solve(Q[i]);
    return 0;
}
發佈了730 篇原創文章 · 獲贊 20 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章