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.
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3831 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | gamegame | 3386 |
10 | ksun48 | 3373 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | awoo | 157 |
6 | adamant | 157 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | Dominater069 | 153 |
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.
Name |
---|
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.
$$$\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:
thanks,love from china