zoukankan      html  css  js  c++  java
  • 题解 luogu P2568 GCD

    题解 luogu P2568 GCD

    时间:2019.3.11

    欧拉函数+前缀和

    题目描述

    给定整数\(N\),求\(1\le x,y \le N\)\(\gcd(x,y)\)为素数的数对\((x,y)\)有多少对.

    分析

    枚举素数\(p\), 先求出\(1\le x,y \le \left \lfloor \dfrac n p \right \rfloor\)\(\gcd(x, y) = 1\)的数对\((x,y)\)有多少对,然后再将\(x,y\)同时乘以\(p\)即可.

    不妨钦定\(x \le y\),如果知道了\(y\),那么\(x\)的数量就是\(\varphi(y)\)\(\text{phi(y)}\))个。对于\(x \ge y\)同理。

    注意数对\((1, 1)\)会被计算两次,答案要减一。

    代码

    #include <bits/stdc++.h>
    using namespace std;
    const int kMaxN = 10000000 + 10;
    typedef long long LL;
    bool is_prime[kMaxN];
    int phi[kMaxN];
    int prime[kMaxN], top;
    int n;
    long long ans, phi_sum[kMaxN];
    void Sieve() {
      memset(is_prime, true, sizeof(is_prime));
      top = 0;
      phi[1] = 1;
      for (int i = 2; i <= n; i++) {
        if (is_prime[i]) {
          prime[++top] = i;
          phi[i] = i - 1;
        }
        for (int j = 1; j <= top && 1ll * i * prime[j] <= n; j++) {
          int p = prime[j];
          is_prime[i * p] = false;
          phi[i * p] = phi[i] * (i % p ? p - 1 : p);
          if (i % p == 0) break;
        }
      }
    }
    int main() {
      scanf("%d", &n);
      Sieve();
      for (int i = 1; i <= n; i++) {
        phi_sum[i] = phi_sum[i - 1] + phi[i];
      }
      for (int i = 1; i <= top; i++) {
        ans += phi_sum[n / prime[i]] * 2 - 1;
      }
      printf("%lld\n", ans);
      return 0;
    }
    
  • 相关阅读:
    266. Palindrome Permutation
    265. Paint House II
    264. Ugly Number II
    263. Ugly Number
    261. Graph Valid Tree
    260. Single Number III
    259. 3Sum Smaller
    pthon 批量压缩当前目录,子目录下图片
    不小心打开了N多的压缩文件窗口,一句命令就搞定!
    # Writing your-first Django-app-part 4-simple-form
  • 原文地址:https://www.cnblogs.com/longlongzhu123/p/10510275.html
Copyright © 2011-2022 走看看