. 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 ≤ 10^7
输出描述: 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
题目大意:1~n 求有多少对数,满足二者除以他们的最大公约数后均为素数。
思路:枚举最大公约数,或直接素筛处理再乘,需要注意的是时间复杂度不能太大,所以普通的素数打表是会超时的。此处应该补充关于素数筛选的知识。传送门:https://www.cnblogs.com/grubbyskyer/p/3852421.html线性筛选
代码如下:
#include <bits/stdc++.h>
using namespace std;
bool prime[10000001]={0};
int main()
{
int n;
long long cnt=0,res=0;
scanf("%d",&n);
for(int i=2;i<=n;++i)
if(prime[i]==0)
{
res+=cnt*(n/i);//个数乘以约数(倍数)
++cnt;//个数加一
for(int j=i*i;j<=n;j+=i)
prime[j]=1;//素数筛选
}
for(int i=2;i<=n;i++) printf("%d ",prime[i]);
printf("%lld\n",res*2);
return 0;
}