UVA 11426 GCD - Extreme (II)(神TM GCD大法,欧拉函数)

Given the value of N, you will have to findthe value of G. The definition of G is given below:

ACM: <wbr>uva <wbr>11426 <wbr>- <wbr>GCD <wbr>- <wbr>Extreme <wbr>(II)

Here GCD(i,j)means the greatest common divisor ofinteger andinteger j.

 

For those who have trouble understandingsummation notation, the meaning of G is given in the followingcode:

G=0;

for(i=1;i<N;i++)

for(j=i+1;j<=N;j++)

{

    G+=gcd(i,j);

}

 

 

Input

The input file contains at most 100 lines ofinputs. Each line contains an integer N(1<N<4000001)

 

Output

For each line of input produce one line ofoutput. This line contains the value of G for the corresponding N.The value of G will fit in a 64-bit signed integer.


 

SampleInput 

10

100

200000

0


Output for SampleInput

67

13015

143295493160


题意:求对于每个i<=N,求f(i)=GCD(1,i)+GCD(2,i)+......GCD(i-1,i)并求前N项和。


对于一个N,设GCD(a,N)=b;则有N=b*x,a=b*y,GCD(a/b,N/b)=1即GCD(x,y)=1;

又依题意得a<N,则Y<X,则满足GCD(a,N)=b且a<N的a的个数等于GCD(y,x)=1且y<x的y的个数,即eluer(x)(小于x且与x互质的数的个数)

因此打个欧拉表再枚举N的约数b即可


代码:

#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<utility>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<math.h>
#include<iterator>
#include<stack>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const double eps=1e-8,PI=3.1415926538;
const LL MOD=1000000000+7;
const LL MAXN=4000007;

LL m[MAXN],phi[MAXN],p[MAXN],pt;

void make()
{
    phi[1]=1;
    LL N=MAXN;
    LL k;
    for(int i=2;i<N;i++)
    {
        if(!m[i])
            p[pt++]=m[i]=i,phi[i]=i-1;
        for(int j=0;j<pt&&(k=p[j]*i)<N;j++)
        {
            m[k]=p[j];
            if(m[i]==p[j])
            {
                phi[k]=phi[i]*p[j];
                break;
            }
            else
                phi[k]=phi[i]*(p[j]-1);
        }
    }
}




LL gcd(LL a,LL b)
{
    if(b==0)return a;
    else return gcd(b,a%b);
}



LL S[MAXN];
int main()
{
    make();
    phi[1]=phi[0]=0;
    memset(S,0,sizeof(S));
    LL z=sqrt(MAXN);
    for(int i=1;i<=z;i++)//枚举N的约数
    {
        for(int j=2;j*i<=MAXN-3;j++)//N=i*j
        {
            S[j*i]+=i*phi[j];
            if(z<j)S[j*i]+=j*phi[i];//z<span style="font-family:Courier New;"><j时,i*j的约数j枚举不到</span>
        }
    }
    LL N,G;
    while(scanf("%lld",&N)!=-1&&N!=0)
    {
        G=0;
        for(int i=2;i<=N;i++)
        {
            G+=S[i];
        }
        printf("%lld\n",G);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值