牛客网暑期ACM多校训练营(第三场)H Diff-prime Pairs 数字 简单思维

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

Diff-prime Pairs

时间限制: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 ≤ 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

题意:给一个n,在【1,n】中找出所有的对数(i,j)( i != j) && ( i,j<=n ) 

并且 = gcd(i,j)为i,j 的 最大公约数

思路 : 1.先在【1,n】中找出所有的素数的个数 ans,并标记号(素数筛选法)

             2.  总数 Ans=ans*(ans-1);  每 一个素数与(其他的素数)进行两两配对

             比如当n=5 时 一开始 素数(2.3.5)对有Ans=ans*(ans-1)=6; {(2.3)(2.5)(3.2)(3.5)(5.2)(5.3) }

          3.找出 符合条件素数对的倍数  

          比如当n=6时一开始 素数(2.3.5)对有Ans=ans*(ans-1)=6 还有两个符合条件的 (2*2.3*2)即(4.6)和(6.4);

代码实现:

#include<bits/stdc++.h>
using namespace std;
const int M=10000010;
bool  a[M];
int  sum[M];
int main()
{
  int i,j,n,m;
  long long ans=0;
  scanf("%d",&n);
  
  memset(a,1,sizeof a);//素数筛选法
  a[1]=0;
  for(i=2; i<=n; i++)
    if(a[i])
    {
       for(j=2;j*i<=n;j++)
        a[j*i]=0;
    }

    for(i=2;i<=n;i++)//记录一共有多少个素数
        if(a[i]) ans++,sum[i]=ans;//sum[i] i点之前有一共多少个素数
       
    ans=ans*(ans-1);//素数对
    for(i=n;i>=3;i--)
    {
        if(a[i])//素数
        {
            int t=n/i;//有多少个可满足条件的 素数倍数
            t--;sum[i]--;//减去素数本身 
            ans+=(2*t*sum[i]);//新增的非素数对 *2是因为(4.6)(6.4);
        }
    }printf("%lld\n",ans);


}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值