欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

牛客网暑期ACM多校训练营(第三场) H Diff-prime Pairs

程序员文章站 2024-03-14 21:21:23
...

题目链接
 

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 牛客网暑期ACM多校训练营(第三场) H Diff-prime Pairs and 牛客网暑期ACM多校训练营(第三场) H Diff-prime Pairs 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.1 ≤ N ≤ 107

输出描述:

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

 

题意:给你一个n,让你求从1到n中满足 i/gcd(i,j)和j/gcd(i,j) 都属素数的(i,j)的个数。

解题思路:

如果i,j自己就是素数的话,那么肯定满足条件,那么如果我们一开始就知道从1到n的范围里素数的个数的话,那么我们就可以得到答案的一部分解,为什么说是一部分,因为还有一部分解来自于素数的倍数(>1)。我们可以知道如果在1~n中,能被i整除的数的个数为n/i 素数已经用完了,那么我们把这个答案-1为剩下的倍数。

然后我只需要统计一下两个 素数的倍数的组合方案数就ok了。我一开始暴力跑,但是超时了,借用了队友的思想。非常棒。

但是竟然还多次提交浮点错误,真是醉了。还是太粗心。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1e7+10;
#define ll long long
ll cnt[maxn],tot,pri[maxn],n;
bool vis[maxn];
void find(){
	memset(vis,0,sizeof(vis));tot=0;
	vis[1]=1;
	ll i,j;
	for(i=2;i<=1e7;i++){
		if(!vis[i]) pri[tot++]=i;
		for(j=0;j<tot&&i*pri[j]<=1e7;j++){
			vis[i*pri[j]]=1;
		} 
	}
}
int main(){
	ll i,j;
	find();
	scanf("%lld",&n);
	ll l;
	for(l=0;pri[l]<=n&&l<tot;l++);
	ll ans=l*(l-1)/2;
	for(i=1;i<l;i++){
		cnt[i]=n/pri[i]-1;
		ans+=i*cnt[i]; 
	}
	printf("%lld\n",ans*2);
	return 0;
}

 

相关标签: 素数筛