zoukankan      html  css  js  c++  java
  • [51nod1188]最大公约数之和 V2

     
    给出一个数N,输出小于等于N的所有数,两两之间的最大公约数之和。
     
     
     
    相当于计算这段程序(程序中的gcd(i,j)表示i与j的最大公约数):
     
    G=0;
    for(i=1;i<N;i++)
    for(j=i+1;j<=N;j++)
    {
        G+=gcd(i,j);
    }
    Input
    第1行:1个数T,表示后面用作输入测试的数的数量。(1 <= T <= 50000)
    第2 - T + 1行:每行一个数N。(2 <= N <= 5000000)
    Output
    共T行,输出最大公约数之和。
    Input示例
    3
    10
    100
    200000
    Output示例
    67
    13015
    143295493160
    首先明白题目求的是$sum_{i=2}^nsum_{j=1}^{i-1}gcdleft(i,j ight)$
    考虑$sum_{i=1}^{n-1}gcdleft(i,n ight)$这种简化版问题
    枚举$gcd(n,j)=t$,那么$gcd(frac{n}{t},frac{n}{j})=1$,则贡献为$tvarphileft(frac{n}{t} ight)$
    那么$sum_{i=1}^{n-1}gcdleft(i,n ight)=sum_{tmid n,t ot=n}tvarphileft(frac{n}{t} ight)$
    考虑完整版问题
    $ans=sum_{i=2}^nsum_{tmid i,t ot=i}tvarphileft(frac{i}{t} ight)$
    $=sum_{t=1}^nsum_{jtle n,t ot=1}tvarphileft(j ight)$
    把答案弄成前缀和形式,这样就可以$Oleft(nlnn ight)$跑一遍然后$Oleft(1 ight)$回答
     
    #include <cstdio>
    const int maxn = 5000000 + 10;
    typedef long long ll;
    bool mark[maxn] = {false};
    int pri[maxn], prn = 0;
    int phi[maxn];
    ll ans[maxn];
    void shai(){
        phi[1] = 1;
        for(int i = 2; i < maxn; i++){
            if(!mark[i]){
                phi[i] = i - 1;
                pri[++prn] = i;
            }
            for(int j = 1; j <= prn && pri[j] * i < maxn; j++){
                mark[i * pri[j]] = true;
                if(i % pri[j]) phi[i * pri[j]] = phi[i] * (pri[j] - 1);
                else{
                    phi[i * pri[j]] = phi[i] * pri[j];
                    break;
                }
            }
        }
        ans[0] = 0;
        for(int i = 1; i < maxn; i++)
            for(int j = 2; i * j < maxn; j++)
                ans[i * j] += phi[j] * i;
        for(int i = 1; i < maxn; i++) ans[i] += ans[i - 1];
    }
    int main(){
        shai();
        int T, n;
        scanf("%d", &T);
        while(T--){
            scanf("%d", &n);
            printf("%lld
    ", ans[n]);
        }
        return 0;
    }
  • 相关阅读:
    js 前端 table 导出 excel
    js调用RadioButton1
    柱状图
    html锚点定位
    遍历所有lable并赋值
    MiniUI 在线示例
    sql更新语句
    生成word
    打开word
    操作word
  • 原文地址:https://www.cnblogs.com/ruoruoruo/p/7701295.html
Copyright © 2011-2022 走看看