D2. Reverse Card (Hard Version)
D2. Reverse Card (Hard Version)
The two versions are different problems. You may want to read both versions. You can make hacks only if both versions are solved.
You are given two positive integers , .
Calculate the number of ordered pairs satisfying the following conditions:
- , ;
- is a multiple of .
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The first line of each test case contains two integers , ().
It is guaranteed that neither the sum of nor the sum of over all test cases exceeds .
Output
For each test case, print a single integer: the number of valid pairs.
Example
input
6
1 1
2 3
3 5
10 8
100 1233
1000000 1145141
output
0
1
1
6
423
5933961
Note
In the first test case, no pair satisfies the conditions.
In the fourth test case, satisfy the conditions.
解题思路
令 ,则有 ,,且 。对于 ,等价于 。又因为 ,因此有 。
因此 等价于 。
此时考虑能否枚举数对 。事实上 ,同理 ,因此这样的数对最多有 。所以我们直接暴力枚举找到满足 的 和 ,由于此时 最大能取到 ,因此满足 对应的 的数量就是 。
AC 代码如下,时间复杂度为 :
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
void solve() {
int n, m;
scanf("%d %d", &n, &m);
LL ret = 0;
for (int i = 1; i * i < n; i++) {
for (int j = 1; j * j < m; j++) {
if (__gcd(i, j) == 1) ret += min(n / i, m / j) / (i + j);
}
}
printf("%lld\n", ret);
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
solve();
}
return 0;
}
参考资料
Codeforces Round 942 (Div. 1, Div. 2) Editorial:https://codeforces.com/blog/entry/129027
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/18170442
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效