How to find the number of pairs of integers (x,y) such that gcd(x,y) = 1?

`n<=1e6`

`x<y<=n`

time limit = 2s

Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official.
×

# | User | Rating |
---|---|---|

1 | tourist | 3880 |

2 | jiangly | 3669 |

3 | ecnerwala | 3654 |

4 | Benq | 3627 |

5 | orzdevinwang | 3612 |

6 | Geothermal | 3569 |

6 | cnnfls_csy | 3569 |

8 | jqdai0815 | 3532 |

9 | Radewoosh | 3522 |

10 | gyh20 | 3447 |

# | User | Contrib. |
---|---|---|

1 | awoo | 161 |

1 | maomao90 | 161 |

3 | adamant | 156 |

4 | maroonrk | 153 |

5 | -is-this-fft- | 148 |

5 | SecondThread | 148 |

5 | atcoder_official | 148 |

8 | Petr | 147 |

9 | nor | 145 |

10 | TheScrasse | 144 |

Codeforces (c) Copyright 2010-2024 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Jul/23/2024 17:30:26 (l3).

Desktop version, switch to mobile version.

Supported by

User lists

Name |
---|

Euler's totient function is the function $$$\phi(n) =$$$ the number of numbers $$$\le n$$$ and coprime to $$$n$$$. Sum that for all $$$y$$$ from $$$2$$$ to $$$n$$$

Hint: DP.

Solution: Let us solve the more general problem: how do you find the number of pairs ($$$p[d]$$$) of integers $$$(x, y)$$$ with a gcd of $$$d$$$?

Let $$$cnt[x]$$$ mean the number of times $$$x$$$ occurs

as a divisor of a numberin $$$a$$$. We would calculate this by iterating over all $$$a_i$$$ and finding its divisors, incrementing $$$cnt[d]$$$ for each divisor (in $$$O(n \sqrt[3]{n}$$$)What if $$$d=\max{a_i}$$$? Then the answer is $$$\frac{cnt[d] \cdot (cnt[d]-1)}{2}$$$. Otherwise, let us initialize the answer for some $$$x<\max{a_i}$$$ to $$$\frac{cnt[x] \cdot (cnt[x]-1)}{2}$$$. This is

almostcorrect, but will also count pairs with a gcd of $$$2x$$$, $$$3x$$$, $$$4x$$$, and so on. So we will subtract $$$p[2x]$$$, $$$p[3x]$$$, $$$p[4x]$$$. This will take $$$O(n \log{n})$$$ time.Here's my code for Counting Coprime Pairs on CSES. Hope this helped!

It can be done fast using mobius inversion: https://mirror.codeforces.com/blog/entry/53925