PAT (Basic Level) Practice (中文)1007 素数对猜想 (20 分)

时间:2022-07-26
本文章向大家介绍PAT (Basic Level) Practice (中文)1007 素数对猜想 (20 分),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1007 素数对猜想 (20 分)

让我们定义d​n​​为:d​n​​=p​n+1​​−p​n​​,其中p​i​​是第i个素数。显然有d​1​​=1,且对于n>1有d​n​​是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。

现给定任意正整数N(<10​5​​),请计算不超过N的满足猜想的素数对的个数。

输入格式:

输入在一行给出正整数N

输出格式:

在一行中输出不超过N的满足猜想的素数对的个数。

输入样例:

20

输出样例:

4

暴力找出素数,遍历一遍判断即可~

// luogu-judger-enable-o2
#include<bits/stdc++.h>
#include<unordered_set>
#define rg register ll
#define inf 2147483647
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
#define ll long long
#define maxn 300005
#define lb(x) (x&(-x))
const double eps = 1e-6;
using namespace std;
inline ll read()
{
	char ch = getchar(); ll s = 0, w = 1;
	while (ch < 48 || ch>57) { if (ch == '-')w = -1; ch = getchar(); }
	while (ch >= 48 && ch <= 57) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
	return s * w;
}
inline void write(ll x)
{
	if (x < 0)putchar('-'), x = -x;
	if (x > 9)write(x / 10);
	putchar(x % 10 + 48);
}
ll n,ans[maxn],tot;
inline bool is(ll x)
{
    if(x<=1)return 0;
    if(x==2||x==3)return 1;
    for(rg i=2;i*i<=x;i++)
    {
        if(x%i==0)return 0;
    }
    return 1;
}
int main()
{
    cin>>n;
    for(rg i=1;i<=n;i++)
    {
        if(is(i))ans[++tot]=i;
    }
    ll sum=0;
    for(rg i=1;i<tot;i++)
    {
        if(ans[i+1]-ans[i]==2)sum++;
    }
    cout<<sum<<endl;
    return 0;
}