牛客2018暑假多校训练营3

比赛链接

牛客2018暑假多校训练营3

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,jN. 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 i1i2orj1j2.

输入描述:

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,jN

示例1

输入

3

输出

2

示例2

输入

5

输出

6

解题思路

题目要找的即:满足这样的素数对 (prime1,prime2),且 max(prime1,prime2)×dn,不妨先把素数筛出来,再求出满足条件的 d 的个数
很容易,有个暴力代码:

long long res=0; for(int i=1;i<=m;i++) for(int j=i+1;j<=m;j++) res+=n/prime[j]; res*=2;

会超时~
分别考虑求 prime[1]prime[2]prime[3]prime[m] 的次数很容易简化代码~

  • 时间复杂度:O(n)

代码

#include<bits/stdc++.h> using namespace std; const int N=1e7+10; int prime[N]; int m,n; int v[N]; void primes(int n) { for(int i=2;i<=n;i++) { if(!v[i]) { v[i]=i; prime[++m]=i; } for(int j=1;j<=m;j++) { if(v[i]<prime[j]||i*prime[j]>n)break; v[i*prime[j]]=prime[j]; } } } int main() { scanf("%lld",&n); primes(n); long long res=0; for(int i=1;i<=m-1;i++) res+=1ll*n/prime[i+1]*i; printf("%lld",res*2); return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/15364399.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(41)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示