2818: Gcd
Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 4502 Solved: 1994
[Submit][Status][Discuss]
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
Source
和上一道题 2190仪仗队 很像,只是这次不是要求gcd(x,y)为1,而是质数(独孤大神告诉我,1不是素数,2333)。
可以先处理出$x,y leq N$下使得$gcd(x,y)=1$的数对个数,记为$ans_{N}$,这个还是可以用$phi_{i}$的求和做到,然后枚举gcd是素数$i$,其答案为$ans_{frac{n}{i}}$,累加即可。
1 #include <bits/stdc++.h> 2 typedef unsigned long long ull; 3 const int siz = 10000005; 4 int n, pri[siz], isp[siz], tot; ull phi[siz], ans[siz]; 5 signed main(void) { 6 scanf("%d", &n); 7 for (int i = 2; i <= n; ++i) { 8 if (!isp[i])pri[tot++] = i, phi[i] = i - 1; 9 for (int j = 0; j < tot; ++j) { 10 if (i * pri[j] > n)break; 11 isp[i * pri[j]] = 1; 12 if (i % pri[j]) 13 phi[i * pri[j]] = phi[i] * (pri[j] - 1); 14 else { 15 phi[i * pri[j]] = phi[i] * pri[j]; break; } 16 } 17 } 18 ans[1] = 1; 19 for (int i = 2; i <= n; ++i) 20 ans[i] = ans[i - 1] + phi[i] * 2; 21 ull answer = 0; 22 for (int i = 0; i < tot && pri[i] <= n; ++i) 23 answer += ans[n / pri[i]]; 24 std::cout << answer << std::endl; 25 }
@Author: YouSiki