牛客多校赛第三场-h题

8. 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 isgiven N, you need to find the number of pairs (i, j), where  and  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.
NOWCODER.COM 牛客网-中国最大IT笔试/面试题库
牛客出品-http://www.nowcoder.com
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

#include<stdio.h>
#include<string.h>
int prime[1000005];
int main()
{
	int k=0;
	int ans=0;
	int n;
	scanf("%d",&n);
	memset(prime,1,sizeof(prime)); 
	prime[0]=0;
	prime[1]=0;
	for(int i=1;i<=n;i++)
	{
		if(prime[i])
		{
			ans=ans+k*(n/i);//前面k个素数和素数i同时1-(n/i)组成一对(i,j),由于k从零开始故两个相同的素数这种情况已被删除; 
			for(int j=i;j<=n;j+=i)
			prime[j]=0;
			k++;	
		}			
	}
	printf("%d",ans*2);
 } 

猜你喜欢

转载自blog.csdn.net/s_h_w_s_n_g/article/details/81231323