bzoj2818: Gcd

2818: Gcd

Time Limit: 10 Sec  Memory Limit: 256 MB

Description

给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的
数对(x,y)有多少对.

 

Input

一个整数N

Output

如题

Sample Input

4

Sample Output

4

HINT

 

hint

对于样例(2,2),(2,4),(3,3),(4,2)


1<=N<=10^7

 

Source

湖北省队互测

 

枚举每个素数p;

求有多少对Gcd(x/p,y/p)=1,

相当于∑ ∑¢(y/p);

 

Code:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAXN 5000007
using namespace std;

long long add[MAXN],ans;
int phi[MAXN*2],prime[MAXN];
bool flag[MAXN*2];
int n,tot; 

void init(){
    phi[1]=1;
    for(int i=2;i<=n;i++){
        if(!flag[i]){
            flag[i]=1;
            prime[++tot]=i;
            phi[i]=i-1;
        }
        for(int j=1;j<=tot&&i*prime[j]<=n;j++){
            flag[i*prime[j]]=1;
            if(i%prime[j]==0){
                phi[i*prime[j]]=phi[i]*prime[j];
                break;
            }else{
                phi[i*prime[j]]=phi[i]*phi[prime[j]];
            }
        }
    }
}

int main(){
    scanf("%d",&n);
    ans=tot=0;
    init();
    for(int i=1;i<=n/2;i++)
        add[i]=add[i-1]+phi[i];
    for(int i=1;i<=tot;i++)
        ans+=add[n/prime[i]];
    printf("%lld",ans*2-tot);
}

 

posted @ 2018-02-07 17:53  JSC!  阅读(205)  评论(0编辑  收藏  举报