itachi_fam's blog

By itachi_fam, history, 16 months ago, In English

given n,k find the number of pair x,y such that gcd(x,y)==k where 1<=x,y<=n and n,k ->1e6.

  • Vote: I like it
  • +1
  • Vote: I do not like it

| Write comment?
»
16 months ago, # |
Rev. 2   Vote: I like it +2 Vote: I do not like it

If gcd(x, y) = k than x and y are both divisible by k. Also gcd(x / k, y / k) = 1. Let x / k = x1, y / k = y1.

Now our problem is to count number of coprime pairs such that x1 * k <= n && y1 * k <= n. Another way to write it is x1 <= int(n / k) and y1 <= int(n / k). Let n1 = int(n / k).

Using Sieve of Eratothenes we can find every prime divisor of numbers <= n1. Now let's iterate once more from 1 to n1. Let P be the array of prime divisors for every number from 1 to n1. For every number i there are i * ∏((P[i][j] — 1)/P[i][j]) (https://en.wikipedia.org/wiki/Euler%27s_totient_function) coprime numbers in range from 1 to i. So, for number of unordered pairs we should just add up all products for every i. For number of ordered pairs we might change the Euler's function to n1 * ∏((P[i][j] — 1)/P[i][j]) for every i.

Time complexity is O(nlogn) while n1 <= n and there are no more than log(n1) prime divisors for every number.

»
16 months ago, # |
Rev. 10   Vote: I like it 0 Vote: I do not like it

$$$\sum\limits_{x=1}^{n}\sum\limits_{y=1}^{n}[gcd(x,y)=k]=\sum\limits_{kx=1}^{n}\sum\limits_{ky=1}^{n}[gcd(kx,ky)=k]=\sum\limits_{x=1}^{\lfloor\frac {n}{k}\rfloor}\sum\limits_{y=1}^{\lfloor\frac {n}{k}\rfloor}[gcd(kx,ky)=k]=$$$ $$$ \sum\limits_{x=1}^{\lfloor\frac {n}{k}\rfloor}\sum\limits_{y=1}^{\lfloor\frac {n}{k}\rfloor}[gcd(x,y)=1]=\sum\limits_{x=1}^{\lfloor\frac {n}{k}\rfloor}\sum\limits_{y=1}^{\lfloor\frac {n}{k}\rfloor}\sum\limits_{d|gcd(x,y)}\mu(d)=\sum\limits_{x=1}^{\lfloor\frac {n}{k}\rfloor}\sum\limits_{y=1}^{\lfloor\frac {n}{k}\rfloor}\sum\limits_{d=1}^{\lfloor\frac {n}{k}\rfloor}[d|x][d|y]\mu(d)=\sum\limits_{d=1}^{\lfloor\frac {n}{k}\rfloor}{\lfloor\frac {n}{kd}\rfloor}^2\mu(d)$$$

and we can get mu by:

int mu[N];
vector<int> isp(N, 1);
vector<int> p;
void init() {
    isp[0] = isp[1] = 0;
    mu[1] = 1;
    for (int i = 2;i < N;i++) {
        if (isp[i]) {
            p.push_back(i);
            mu[i] = -1;
        }
        for (auto j : p) {
            if (i * j < N) {
                isp[i * j] = 0;
                if (i % j == 0) {
                    break;
                }
                else {
                    mu[i * j] = -mu[i];
                }
            }
            else {
                break;
            }
        }
    }
}