牛客暑期训练营 第三场 H 题

25 篇文章 0 订阅

来源:牛客网
 

题目描述

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

题目大意就是找出一对 (i,j) <= n  且  and  都是质数的情况,

分析可知 若他们的最大公约数是 k 那么i=a*k,j=b*k; 且 a ,b一定都是质数,找出最大的k 即 n/i ,那可取的倍数即为 1~k;

在素数筛法的同时找出  每个质数的 k 值 因为质数越来越大 ,n 不变,所以 k值会越来越小,成阶梯型,每多个质数,前面所有的质数的k值一定大于等于新增的;  所以新增的配对个数为 :已找到的质数个数 × 新增质数的 最大倍数 k值,代码如下

#include <bits/stdc++.h>
using namespace std;
bool is_prime[10000001]={0};
int main() {
    int n;
    long long cnt=0,res=0;
    scanf("%d",&n);
    for (int i=2;i<=n;++i)
        if (!is_prime[i]) {
            res+=cnt*(long long)(n/i);
            ++cnt;
            for (int j=i*i;j<=n;j+=i) is_prime[j]=1;
        }
    printf("%lld\n",res*2);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值