NC17247 H、Diff-prime Pairs

题目链接

题目

题目描述

Eddy has solved lots of problem involving calculating the number of coprime pairs within some range. This problem can be solved with inclusion-exclusion method. Eddy has implemented it lots of times. Someday, when he encounters another coprime pairs problem, he comes up with diff-prime pairs problem. diff-prime pairs problem is that given N, you need to find the number of pairs (i, j), where igcd(i,j) and jgcd(i,j) are both prime and i ,j ≤ N. gcd(i, j) is the greatest common divisor of i and j. Prime is an integer greater than 1 and has only 2 positive divisors.

Eddy tried to solve it with inclusion-exclusion method but failed. Please help Eddy to solve this problem.

Note that pair (i1, j1) and pair (i2, j2) are considered different if i1 ≠ i2 or j1 ≠ j2.

输入描述

Input has only one line containing a positive integer N.

1N107

输出描述

Output one line containing a non-negative integer indicating the number of diff-prime pairs (i,j) where i, j ≤ N

示例1

输入

3

输出

2

示例2

输入

5

输出

6

题解

知识点:组合数学,枚举,筛法。

考虑枚举每一对素数 (i,j) 产生的贡献,其中显然 ij

不妨先假设 i<j ,那么形如 (ki,kj) 的一对数结果会是 (i,j) ,其中 knj

我们发现,对于任意的素数 i 满足 i<j ,答案都是 nj ,因此我们可以只枚举 j ,那么以 j 较大数时产生的贡献,答案是 (π(j)1)nj

最后不要忘记乘 2 ,因为我们一开始设 i<j ,为了计数方便。

时间复杂度 O(n)

空间复杂度 O(n)

代码

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e7 + 7;
bool vis[N];
vector<int> prime;
void get_prime(int n) {
for (int i = 2;i <= n;i++) {
if (!vis[i]) prime.push_back(i);
for (auto j : prime) {
if (i * j > n) break;
vis[i * j] = 1;
if (!(i % j)) break;
}
}
}
int main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
get_prime(n);
ll ans = 0;
for (int i = 0;i < prime.size();i++) {
ans += i * (n / prime[i]);
}
cout << ans * 2 << '\n';
return 0;
}
posted @   空白菌  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2022-08-25 NC51180 Accumulation Degree
2022-08-25 NC24263 USACO 2018 Feb G]Directory Traversal
2022-08-25 NC19782 Tree
点击右上角即可分享
微信分享提示