hdu-1695 GCD (Mobius inversion)

Meaning of the questions:

Find x in [1, n] range, y in [1, m] in the range satisfying gcd (x, y) = k x, y, logarithmic.

answer:
  • If f (k) within a range of topics logarithmic gcd (x, y) = k, but this f (k) Comparison of "hard to find." We found that gcd (x, y)% k == x 0 , y, but a good number of requirements. Let's express gcd (x, y)% k == 0 with a number of F (k). In this case I wanted to be able to seek f (k) by F (k). After \ (F (k) = \ sum_ {k | d} f (d) \) which can be used to give Mobius inversion formula

    \[f(k) = \sum_{k|d} \mu(\frac{d}{k})F(d) \]

    \[f(k) = \sum_{k|d} \mu(\frac{d}{k}) \lfloor\frac{n}{d}\rfloor \lfloor\frac{m}{d}\rfloor \]

    We iterate over all d (d is a multiple of k) to sue for peace. Because if \ (GCD (X, Y) =. 1 \) , then \ (gcd (k * x, k * y) = k \) so we can find the above formula f (1)

    \[f(1) = \sum_{d=1}^{lim} \mu(d) \lfloor\frac{n}{d}\rfloor \lfloor\frac{m}{d}\rfloor \]

    Because k * x <= n, k * y <= m. Therefore lim = min (n / k, m / k)

    Complexity of O (n).

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;

int T, k, a, b, c, d;
int pri[N], cnt;
int mu[N];
int vis[N];

void prime(){
    mu[1] = 1;
    for(int i = 2; i <= 4e5; ++ i){
        if(!vis[i]){
            pri[++ cnt] = i;
            mu[i] = -1;
        }
        for(int j = 1; j <= cnt && pri[j] * i <= 4e5; ++ j){
            vis[pri[j] * i] = 1;
            if(i % pri[j] == 0){
                mu[pri[j] * i] = 0;
                break;
            }
            mu[pri[j] * i] = -mu[i];
        }
    }
}


int main()
{
    prime();
    scanf("%d",&T);
    for(int Case = 1; Case <= T; ++ Case){
        scanf("%d%d%d", &b, &d, &k);
        if(!k){
            printf("0\n", Case);
            continue;
        }
        b /= k, d /= k;
        if(b > d) swap(b, d);
        ll ans = 0, ans1 = 0;
        for(int i = 1; i <= b; ++ i) ans += (ll)mu[i] * (b / i) * (d / i);
        for(int i = 1; i <= b; ++ i) ans1 += (ll)mu[i] * (b / i) * (b / i);
        ans -= ans1 / 2;
        printf("%lld\n", ans);
    }
    return 0;
}

Problem solution blog: https://blog.csdn.net/litble/article/details/72804050?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

Guess you like

Origin www.cnblogs.com/A-sc/p/12626444.html