【bzoj2818】Gcd

2818: Gcd

Time Limit: 10 Sec  Memory Limit: 256 MB
Submit: 4344  Solved: 1912
[Submit][Status][Discuss]

Description

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

Input

一个整数N

Output

如题

Sample Input

4

Sample Output

4
 
 
 
 
【题解】
 
用f[i]表示1~i中gcd(a,b)=1的数对(a,b)的对数,那么显然 f[i] = 1+2* sigma(phi[j])  1<j<=i
 
那么ans = sigma(f[N/p])  p为小于N的素数
 
原理很简单,即如果gcd(a,b)=1,那么gcd(a*p,b*p)=p
 
 1 /*************
 2   bzoj 2818
 3   by chty
 4   2016.11.3
 5 *************/
 6 #include<iostream>
 7 #include<cstdio>
 8 #include<cstdlib>
 9 #include<cstring>
10 #include<ctime>
11 #include<cmath>
12 #include<algorithm>
13 using namespace std;
14 #define MAXN 10000010
15 int n,cnt,prime[MAXN],check[MAXN],phi[MAXN];
16 long long f[MAXN],ans;
17 inline int read()
18 {
19     int x=0,f=1;  char ch=getchar();
20     while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getchar();}
21     while(isdigit(ch))  {x=x*10+ch-'0';  ch=getchar();}
22     return x*f;
23 }
24 void get()
25 {
26     phi[1]=1;
27     for(int i=2;i<=n;i++)
28     {
29         if(!check[i])  {prime[++cnt]=i;  phi[i]=i-1;}
30         for(int j=1;j<=cnt&&prime[j]*i<=n;j++)
31         {
32             check[i*prime[j]]=1;
33             if(i%prime[j])  phi[i*prime[j]]=phi[i]*(prime[j]-1);
34             else {phi[i*prime[j]]=phi[i]*prime[j];  break;}
35         }
36     }
37 }
38 int main()
39 {
40     freopen("cin.in","r",stdin);
41     freopen("cout.out","w",stdout);
42     n=read();
43     get();
44     f[1]=1;
45     for(int i=2;i<=n;i++)  f[i]=f[i-1]+2*phi[i];
46     for(int i=1;i<=cnt;i++)
47         if(prime[i]<n)  ans+=f[n/prime[i]];
48     printf("%lld
",ans);
49     return 0;
50 }
 
原文地址:https://www.cnblogs.com/chty/p/6028325.html