链接:https://www.nowcoder.com/acm/contest/141/H
来源:牛客网
题目描述
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 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.
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
一直没找到规律。。。比赛的时候发现越找越多了 心态爆炸
正解思路:(我猜是打表找的规律?我队有人打表,打了两个小时,最后在赛后过了emmmmm)
每次取到其中两个素数组成一个素数对(x, y),不妨设 x < y,那么相应的就增加了 2×⌊n/y⌋2×⌊n/y⌋ 个数对;
例如,n=7,取到素数对(2,3),那么 ⌊n/3⌋=⌊7/3⌋=2⌊n/3⌋=⌊7/3⌋=2,就有 2×2=42×2=4 个数对:(1*2,1*3) = (2,3)、(3,2)、(2*2,2*3) = (4,6)、(6,4);
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e7+5;
int n;
ll ans;
bool isPrime[maxn];
int prime[maxn/10],cnt;
void screen()//欧拉筛法求素数
{
cnt=0;
memset(isPrime,1,sizeof(isPrime));
isPrime[0]=isPrime[1]=0;
for(int i=2;i<=n;i++)
{
if(isPrime[i])
{
prime[cnt++]=i;
ans+=2*(n/i)*(cnt-1);
//每找到一个素数i,其就可以与前面所有出现过的cnt-1个素数组成cnt-1个素数对,相应的就有2*(n/i)*(cnt-1)个数对
}
for(int j=0;j<cnt;j++)
{
if(i*prime[j]>n) break;
isPrime[(i*prime[j])]=0;
if(i%prime[j]==0) break;
}
}
}
int main()
{
scanf("%d",&n);
ans=0;
screen();
cout<<ans<<endl;
}