H Diff-prime Pairs

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

 

题目:

 链接:https://www.nowcoder.com/acm/contest/141/H
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

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

 

思路:

  遍历每个g,找到两个不同的素数p1,p2,如果g*p1<=n 并且 g*p2<=n,那么(g*p1,g*p2)就是一个符合要求的素数对,

那问题就转化成找 n/g 以内的素数的数量,可以通过线性筛出素数再处理前缀和得出。对于每个g,小于g的素数数量为cnt=pre[n/i],则符合要求的素数对数量为C(cnt,2),因为可以交换顺序,所以是C(cnt,2)*2;

代码:

#include<cstdio>
using namespace std;
const int maxn = 11000000;
bool vis[maxn];
int prime[maxn];
int pre[maxn];

int main()
{
    ///先线性筛出素数
    int top=0,maxn=1e7+2;
    long long i,j;
    for( i=2; i<=maxn; i++)
    {
        if(!vis[i])prime[top++]=i;
        for(int j=0; prime[j]*i<maxn; j++)
        {
            vis[ prime[j]*i ]=1;
            if(i%prime[j]==0)break;
        }
    }
    ///预处理前缀和,找出小于等于i的质数的个数
    vis[1]=1;
    for(int i=1; i<=maxn; i++)
    {
        pre[i]=pre[i-1]+!vis[i];
    }


    int n;
    scanf("%d",&n);
    long long ans=0;
    for(int i=1; i<=n; i++)
    {
        long long cnt = pre[n/i];
        if(cnt>=2)
            ans+=(cnt-1)*cnt;  /// C(N,2)*2 
    }
    printf("%lld
",ans);

    return 0;
}
原文地址:https://www.cnblogs.com/longl/p/9375755.html