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

题目链接:http://henuly.top/?p=643

题目:

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 img%7D) and img%7D) 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:

Input has only one line containing a positive integer N.

1 ≤ N ≤ 107

Output:

Output one line containing a non-negative integer indicating the number of diff-prime pairs (i,j) where i, j ≤ N

Sample Input:

3

Sample Output:

2

Sample Input:

5

Sample Output:

6

题目链接

比赛前期解这道题的时候直接跳过了枚举的想法,以为要推公式,局限在了组合数公式中,后来感觉越推越迷就尝试着写了一下暴力,还真过了,看来有些签到题目该直接上还是要直接上啊。

先用筛法打表素数,直接在 2 n 中间找到所有素数,通过 n / i 判断 i 和另一个素数 j ( j < i ) 是否可以同时扩大 k 倍组成另一组 i j 使得img%7D)和img%7D)也是一组解,计数加结果。

AC代码:

#pragma comment(linker, "/STACK:102400000,102400000")
#include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define mp make_pair
#define lowbit(x) (x&(-x))
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<double,double> PDD;
const int INF = 0x3f3f3f3f;
const int maxn = 1e7 + 5;
const int mod = 1e9 + 7;
const double eps = 1e-8;
const double pi = asin(1.0) * 2;
const double e = 2.718281828459;
bool Finish_read;
template<class T>inline void read(T &x){Finish_read=0;x=0;int f=1;char ch=getchar();while(!isdigit(ch)){if(ch=='-')f=-1;if(ch==EOF)return;ch=getchar();}while(isdigit(ch))x=x*10+ch-'0',ch=getchar();x*=f;Finish_read=1;}

int n;
int cnt;
ll ans;
bool IsPrime[maxn];

void Prime() {
    mem(IsPrime, 1);
    for (ll i = 2; i < maxn; ++i) {
        if (IsPrime[i]) {
            for (ll j = i * i; j < maxn; j += i) {
                IsPrime[j] = 0;
            }
        }
    }
    IsPrime[1] = 0;
}

int main(int argc, char *argv[]) {
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    Prime();
    read(n);
    cnt = 0;
    ans = 0;
    for (int i = 2; i <= n; ++i) {
        if (IsPrime[i]) {
            ans += (n / i) * cnt;
            cnt++;
        }
    }
    printf("%lld\n", ans * 2);
#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
    system("gedit out.txt");
#endif
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tony5t4rk/article/details/81229035
今日推荐