BZOJ 2818: Gcd(欧拉函数)
GCD
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
分析:
如果两个数字x,y,它们互质则
由gcd(x,y)=1
可知gcd(x*p[i],y*p[i])=p[i]
现在这个问题就变成了对于1~n的每个质数p[i],1~n/p[i]中互质的数个数对记为v[i],求∑v[i]
先求欧拉函数表,对于每个质数,当x<=y时 对数=∑e[k](1<=k<=p[i]), 当y<=x时对数也一样,由于(1,1)多算了一次,故减去1
v[i]=∑e[k](1<=k<=p[i])*2-1
program asdf; var e,prime:array[0..10000005]of int64; n,i,m:longint; ans,p:int64; procedure work; var i,j:longint; begin p:=0; for i:=0 to n do e[i]:=i; for i:=2 to n do if e[i]=i then begin j:=i; while j<=n do begin e[j]:=e[j] div i*(i-1); inc(j,i); end; end; for i:=1 to n do begin if e[i]=i-1 then begin inc(p); prime[p]:=i; end; end; end; begin readln(n); work; for i:=1 to n do inc(e[i],e[i-1]); for i:=1 to p do inc(ans,2*e[n div prime[i]]-1); writeln(ans); end.