【歐拉函數+線性篩】bzoj2818: Gcd

biu~題目在這裏

Description

給定整數N,求1<=x,y<=N且Gcd(x,y)爲素數的
數對(x,y)有多少對.

Input

一個整數N

Output

如題

Sample Input

4

Sample Output

4

HINT

對於樣例(2,2),(2,4),(3,3),(4,2)
1<=N<=10^7

思路

枚舉n內每個質數,然後每個質數p對答案的貢獻就是(1~n/p)中有序互質數對的個數
而求1~n中有序互質對x,y的個數時,可以令y>=x,當y==x時,有且只有y=x=1互質,當y>x時,符合條件的數目就是y的歐拉值
所以,n內有序互質數對的個數爲(1~n/p)的歐拉函數之和*2-1(減去(1,1))
所以,首先我們線性篩出n內的質數,同時我們還可以求出每個數的歐拉函數的歐拉值
再求歐拉函數的前綴和即可

代碼

#include <bits/stdc++.h>
using namespace std;
inline int read(){
    int ret=0,f=1;char c=getchar();
    for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
    for(;isdigit(c);c=getchar())ret=ret*10+c-'0';
    return ret*f;
}
const int N=1e7+7;
bitset<N>pl;
int n,a[N],pp=0;
long long phi[N],sum[N],ans=0;
void getphi(){
    phi[1]=1;
    for(int i=2;i<=n;++i){
        if(!pl[i]) a[++a[0]]=i,phi[i]=i-1;
        for(int j=1;j<=a[0];++j){
            int x=a[j];
            if(i*x>n)break;
            pl[i*x]=1;
            if(i%x==0){
                phi[i*x]=phi[i]*x;break;
            }else phi[i*x]=phi[i]*phi[x];
        }
    }
}
int main(){
    n=read();
    getphi();
    for(int i=1;i<=n;++i)sum[i]=sum[i-1]+phi[i];
    for(int i=1;i<=a[0];++i)ans+=sum[n/a[i]]*2-1;
    printf("%lld",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章