1. 程式人生 > >Extreme (II)(神TM 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)

HereGCD(i,j)means the greatest common divisor ofintegeriandinteger 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;
}