Acwing 220 最大公約數
阿新 • • 發佈:2020-08-02
題意:
給定整數對$N$, 求$1 \leq x, y \leq N$ 且$gcd(x, y)$為質數的數對$(x, y)$有多少對
思路:
列舉$1 ~ N$所有質數$p$,$gcd(x, y) = p$即$gcd(\frac{x}{p}, \frac{y}{p}) = 1$,則統計$1 \leq x, y \leq \frac{N}{p}$內有多少個數對$(x, y)$滿足$gcd(x, y) = 1$即可
如何統計:對每個數x記錄與其互質的數的數量(尤拉篩)並預處理尤拉函式的字首和,列舉質數$p$,$ans +=(sum[n/p] * 2 - 1)$(其中$sum[n/p]$為$1 \leq x, y \leq \frac{N}{p}$的尤拉函式字首和,乘$2$是因為所得的所有$(x, y)$為一個解,$(y, x)$也是一個解。減$1$是因為當$x = 1$時,$y = 1$,則$(x, y) (y, x)$都為$(1, 1)$,會重複)
Code:
#pragma GCC optimize(3) #pragma GCC optimize(2) #include <map> #include <set> // #include <array> #include <queue> #include <stack> #include <vector> #include <cstdio> #include <cstring> #include <sstream> #include <iostream> #include<stdlib.h> #include <algorithm> // #include <unordered_map> using namespace std; typedef long long ll; typedef pair<int, int> PII; #define Time (double)clock() / CLOCKS_PER_SEC #define sd(a) scanf("%d", &a) #define sdd(a, b) scanf("%d%d", &a, &b) #define slld(a) scanf("%lld", &a) #defineslldd(a, b) scanf("%lld%lld", &a, &b) const int N = 1e7 + 20; const int M = 1e6 + 20; const int mod = 1e9 + 7; int n, m; ll sum[N]; bool st[N]; int primes[N], cnt, phi[N]; void get(int n){ phi[1] = 1, sum[1] = 1; for(int i = 2; i <= n; i ++){ if(!st[i]){ primes[cnt ++] = i; phi[i] = i - 1; } sum[i] = sum[i - 1] + phi[i]; for(int j = 0; primes[j] <= n / i; j ++){ st[i * primes[j]] = true; if(i % primes[j] == 0){ phi[i * primes[j]] = primes[j] * phi[i]; break; } phi[i * primes[j]] = (primes[j] - 1) * phi[i]; } } } void solve() { sd(n); ll ans = 0; for(int i = 0; primes[i] <= n; i ++){ ans += (sum[n / primes[i]] * 2 - 1); } cout << ans << endl; } int main() { #ifdef ONLINE_JUDGE #else freopen("/home/jungu/code/in.txt", "r", stdin); // freopen("/home/jungu/code/out.txt", "w", stdout); #endif // ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); int T = 1; get(N - 20); // sd(T); while (T--) { solve(); } return 0; }