PAT 1007 素数对猜想

PAT 1007 素数对猜想

 

让我们定义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

 思路:使用两个数不断更新素数,re,lt;当有新的素数出现时,判断其是否相差2,是则计数器+1;然后更新re的值。使用这个大佬写的判断素数的方法,遍历一遍即可。代码如下:

#include <iostream>
#include <math.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <queue>
#include <vector>
#include <string>
#include <sstream>
#include <set>
#include <stack>
#include <map>
#include <utility>
#define LL long long
using namespace std;
bool judge(int x){
	if(x==2||x==3)return true;
	if(x%6!=1&&x%6!=5)return false;
	int tmp=sqrt(x);
	for(int i=5;i<=tmp;i+=6)if(x%i==0||x%(i+2)==0)return false;
	return true;
}
int main()
{
	int n;
	scanf("%d",&n);
	int num=0;
	int le=2,rt=0;
	for(int i=2;i<=n;i++)
	{
		if(judge(i)){
			rt=i;
			if(le+2==rt)num++;
			le=rt;
		}
	}
	cout<<num<<endl;
	return 0;
}

 

posted @ 2019-07-30 20:30  whocarethat  阅读(98)  评论(0编辑  收藏  举报